Low Orbit Flux Logo 2 F

Linux Command - grep

The linux command grep is used to filter for lines that contain a matching string. You can use it directly on a file but it is also commonly used as a filter when chaining commands together with pipes.

Search for all lines containing ‘abc’ in this file:



grep abc test.txt

Case insensitive search:



grep -i abc test.txt

Invert match, exclude any lines that match:



grep -v abc test.txt

Pipe output from one command into grep.



ps -ef | grep -i nginx

Use a regex but need to escape characters such as this one:



grep "abc\|xyz" test.txt

Use extended regular expressions. Don’t need to escape characters:



grep -E "abc|xyz" test.txt

Search for two patterns and match either:



grep -e "abc" -e "xyz" test.txt

Obtain patterns to match from a file:



grep -f patterns.txt test.txt

Highlight matches with color:



grep --color abc test.txt

Just show count of matches:



grep -c abc test.txt

Show name of each file with no match:



grep -L *

Name of each file with a match:



grep -l *       

Stop reading after this many matches:



grep -m 1 abc test.txt

Search for ‘abc’ recursively:



grep -r abc

Search for ‘abc’ recursively and follow symlinks:



grep -R abc

Search for ‘abc’ recursively but exclude matching files:



grep --exclude=*.py -r abc

-E extended regular expressions
-F fixed strings ( not regex )
-G basic regular expressions ( default )
-P perl compatible regular expressions