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

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

cat

Print file contents, number lines, and join multiple files together.

grep

Find lines matching a pattern in files or piped input — the workhorse of text search.

More how-to guides

Check disk space in Linux

See how much space is left, and find out what is using it.

Extract a .tar.gz archive

Unpack tar.gz, tar.bz2, tar.xz and zip archives from the command line.

Free a port that is already in use

Find which process holds a port and stop it cleanly.

Find and replace text in files

Replace text in one file or across a whole project, safely.