How to Count Lines in a File in Linux
Count lines, words and bytes with wc, with useful variations for logs and source files.
`wc` is the small Unix utility for counting lines, words, characters and bytes. It is useful in scripts because its output is predictable and easy to pipe into other commands.
Step by step
1 Count lines
$ wc -l file.txt Prints the number of newline characters and the filename.
2 Count several files
$ wc -l *.log Shows a count for each matching file plus a total.
3 Count lines from a pipeline
$ grep -i "error" app.log | wc -l Counts the number of matching output lines.
4 Count words and bytes too
$ wc file.txt Without options, wc reports lines, words, bytes and the filename.
Tips worth knowing
- For source-code statistics, remember that blank and comment lines are still lines.
- When counting command output, prefer `wc -l` over parsing formatted output with shell string operations.
- A final line without a newline can make intuitive line counting differ from wc -l.
Frequently asked questions
How do I count lines in Linux?
Use `wc -l file.txt`.
How do I count matching lines?
Pipe the command into `wc -l`, for example `grep "error" app.log | wc -l`.
Does wc -l count blank lines?
Yes. It counts newline characters, including those ending blank lines.
The commands behind it
Print file contents, number lines, and join multiple files together.
grepFind lines matching a pattern in files or piped input — the workhorse of text search.
More how-to guides
See how much space is left, and find out what is using it.
Extract a .tar.gz archiveUnpack tar.gz, tar.bz2, tar.xz and zip archives from the command line.
Free a port that is already in useFind which process holds a port and stop it cleanly.
Find and replace text in filesReplace text in one file or across a whole project, safely.