Sunday, July 17, 2011

grep oneliner: get the line you want and its neighbors

Grep is great for printing out a line (or multiple lines) that match a given value. However, I have found it sometimes helpful to search large files, especially log files, at get the line I want plus a few before and after.

If I want to find errors in the /var/log/messages file and I know the line will contain the word "ERROR", I can use the below to get all the lines matching (case-sensitive in this example) as well as 3 before and 3 after.

grep ERROR -B 3 -A 3 /var/log/messages