How To: search with grep

To search through text you can use the grep command. It searches files and returns the lines of the file that match a certain string.

The command has the following format:

grep [options] pattern [file]



Here are some of the useful options I use:

-imatch case insensitive
-nInclude line number of match in output
-rSearch recursively through directories
-Ftreat regex litteraly
-mSpecify the maximum number of matches outputed
-H / -hInclude filename / Do not include filename
-ASpecify number of trailing lines after match
-BSpecify number of leading lines before match
-oOnly output the matched word, not the whole line
-lOutput only the names of files containing match
--colourhighlight the matched keyword in the output line



You can also search multiple files eg. all files ending with ‘.log’:

grep "error" "*.log"

And specify multiple patterns:

grep "error|warning" "*.log"

Let’s make some example commands

Highlight the matched word, specify file name and line number and search case insensitively:

grep --colour -Hni "error" "file.txt"

Recursively search in a specified directory

grep -r "error" ./directory

Search all files in current directory with .log extension. Highlight output, maximum number of matches 2, print 1 leading and 1 trailing line

grep --colour -m2 -A1 -B1 "error" "*.log"

Search through directory and only specify name of file containing the match

grep -rl "searchString" /path


Aight, go search!

Leave a Reply

Your email address will not be published.