Grep notes

Some notes on grep, the pattern matching program found on most Linux distributions.

Show partial lines on match

Grep doesn’t have an option to show leading/trailing characters before/after the match. Instead you have to prevent it returning the entire line (with the -o flag) and use a regular expression to determine what to match.

For example, to search for “test” in thefile.txt and return the matches with all trailing characters but a space:

grep -o "test[^ ]*" thefile.txt


me@pc ~ $ echo "This is a test file for testing grep." > thefile.txt
me@pc ~ $ grep -o "test[^ ]*" thefile.txt 

Show context

Grep can show surrounding lines with the -C[n] flag.

Show only the match

To show only the match, not the entire line as by default, use the -o flag.

Output 0 or 1

grep -cm1

The c flag causes grep to output a count of matches and m1 sets the max count to 1 causing grep to exit as soon as a match is found.


me@pc ~ $ echo foo | grep foo -cm1
me@pc ~ $ echo bar | grep foo -cm1

Recursive grep and filename wildcards

You can call grep with the -r switch to make it search recursively.

To search all files under /dir for “blah”, run the following:

grep -r blah /dir

You can not use wildards directly in this manner, for example, the following will not search all text files:

grep -r blah *.txt

This doesn’t work because the wildcard is expanded by the shell before grep is called. Instead, search the current directory (or whichever one you want) and pass the –include option:

grep -r blah . --include "*.txt"

Grep only text files

To recursively grep all text files in the current directory:

grep foo -rI .

The -I flag tells grep to ignore binary files.


Last modified: 30/08/2015 Tags:

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top