Taco Steemers

A personal blog.
☼ / ☾

Notes on grep

Table of contents:

Basics

A basic search:

grep "search pattern" filename_path

A case-insensitive search:

grep -i "search pattern" filename_path

Text has to be at the start of the line:

grep "^text" filename_path

Printing the line number in the output:

grep -n "search pattern" filename_path

Printing 3 lines before the match, and 5 lines after the match:

grep -n -B 3 -A 5 "search pattern" filename_path

Searching recursively in a directory:

grep -r "search pattern" directory_path

For grepping in ZIP files (archive files) we can use zipgrep.

Practical example

Let's say that something went wrong on a server at a specific time, and you want to search through the server logs. You search for a line that starts with the time hour and minute:

grep "^04:53" server.log

Now you have a starting point, but remember that logging lines with stack traces usually don't start with the time. Those are missing from these grep results.

Maybe there were too many results, and you are only interested in those lines that contain ERROR:

grep "^04:53" server.log | grep ERROR

Hopefully there weren't too many errors at that minute.

Now you see an error you are interested in, at 4:53:17. Let's get that error and a number of lines after that

grep -A 50 "^04:53:17" server.log

With 50 extra lines we should be able to see the full stack trace. We can use any number we like. -B will give the lines before the match.