Back to course

55. Advanced `grep`: Line Numbers, Counting, and Negation

Linux Basics: From Zero to CLI Hero

Showing Line Numbers (-n)

The -n option displays the line number where the pattern was found.

bash $ grep -n bash /etc/passwd 1:root:x:0:0:root:/root:/bin/bash 10:user:x:1000:1000::/home/user:/bin/bash

Counting Matches (-c)

Instead of printing the lines, -c prints only the count of lines that matched the pattern.

bash $ grep -c 'user' logfile.log 25

25 lines contained the word 'user'

Inverting the Match (Negation, -v)

The -v option inverts the match, showing only the lines that do not contain the pattern.

bash

List all files in /etc that are NOT configuration files (i.e., don't end in .conf)

$ ls /etc | grep -v '.conf'

Recursive Search (-r)

To search for a pattern across all files inside a directory and its subdirectories:

bash $ grep -r '404 Error' /var/log/apache2