CMD Master
Back to Blog
Arnošt Havelka

Count lines with wc and sort a file

Use wc -l to count lines, then sort to put names in order.

Start Interactive Lesson
Count lines with wc and sort a file

Logs and lists are easier to judge when you know how long they are. wc -l prints a line count. sort puts the lines in order so duplicates and gaps are obvious.

Count lines: wc -l

-l means lines (not words or bytes). Pass a filename.

Try the command

Count the lines in a file!

Build the command
wc
Terminal
~$wc -l users.txt
0 users.txt

How many accounts?

Terminal
~$wc -l users.txt

The number comes first, then the filename. Pipe into wc -l when you already filtered with grep.

Put lines in order: sort

sort reads a file and prints the lines alphabetically. It does not change the file unless you redirect the output.

printf '%s\n' 'Zebra' 'Apple' > names.txt
sort names.txt

Zebra then Apple on disk becomes Apple then Zebra on the screen.

Terminal
~$sort names.txt

Count first when you need a size. Sort when you need to scan the values. Combine them later with a pipe: sort names.txt | wc -l.


Knowledge Check

1 / 3

What does wc -l file print?

References

These documentation links provide authoritative details for the commands used in this article.

Up Next

Practice: Data Extraction

Combine grep, pipes, and redirection to extract and analyze data.