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
steph@bpc ~ $ echo "This is a test file for testing grep." > thefile.txt steph@bpc ~ $ grep -o "test[^ ]*" thefile.txt test testing
Grep can show surrounding lines with the
Show only the match
To show only the match, not the entire line as by default, use the
Output 0 or 1
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.
steph@bpc ~ $ echo foo | grep foo -cm1 1 steph@bpc ~ $ echo bar | grep foo -cm1 0
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 .
-I flag tells grep to ignore binary files.