CMD Master
Back to Blog
Arnošt Havelka

Chain grep, sort, and wc in one command

Count matching lines and filter a sorted list by combining cat, grep, sort, and wc.

Start Interactive Lesson
Chain grep, sort, and wc in one command

Once grep, sort, and wc each make sense, the real work is composing them. One line can extract errors from a log and count them, or sort a user list and keep only matching names. There is no special “ninja” command — only pipes.

Count matching lines

Read the file, keep the pattern, count what remains:

Try the command

Filter a file, then count or sort!

Build the command
cat
Terminal
~$cat data.log | grep 'ERROR' | wc -l
2

How many ERROR lines?

Terminal
~$cat data.log | grep 'ERROR' | wc -l

grep without wc still prints the matching lines. Add wc -l when you only need the number.

Sort first, then filter

Sometimes order matters before you search. Sort the file, then keep the line you care about:

printf '%s\n' 'user: guest' 'user: root' 'user: admin' > logs.txt
cat logs.txt | sort | grep 'root'
Terminal
~$cat logs.txt | sort | grep 'root'

Read left to right: produce lines, transform them, then keep or count. If a pipe looks wrong, run each piece alone until the output matches what the next command expects.


Knowledge Check

1 / 3

What does cat data.log | grep 'ERROR' | wc -l return?

References

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

Up Next

How to Change File Ownership with chown in Bash

Use chown to change a file or directory owner and group, verify the result, and avoid unsafe recursive ownership changes.