1

I have a folder with big files (few GB each). I would like to search aPATTERNthrough these files. I can do this with grep or ack:

$ grep -n 'PATTERN' /path/to/files/*.log

Now, I have a list with all lines including PATTERN. However, I need some area includes these lines to see context: few lines before PATTERN occurs and few lines after it occurs. I would prefer to list these line blocks with coordinates of each (file and line number). How it can be done?

4

With gnu grep

grep -B <number_lines> -A <number_lines> -n 'PATTERN' /path/to/files/*.log

e.g. to get the 6 lines above the line grep matched, and 4 lines after it:

grep -B 6 -A 4 -n 'PATTERN' /path/to/files/*.log

From man grep

Context Line Control
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.