I have to parse a very large file and I want to use the command grep (or any other tool).
I want to search each log line for the word FAILED
, then print the line above and below each matching line, as well as the matching line.
id : 15 Satus : SUCCESS Message : no problem
id : 15 Satus : FAILED Message : connection error
And I need to print:
id : 15 Satus : FAILED Message : connection error
It is possible to print a line above or below (or both) a line having a pattern using grep by using -A , -B or -C flags with num value. Here num denotes the number of additional lines to be printed which is just above or below the matched line.
Use the -A argument to grep to specify how many lines beyond the match to output. And use -B n to grep lines before the match. And -C in grep to add lines both above and below the match!
You can use the -B and -A to print lines before and after the match. Will print the 10 lines before the match, including the matching line itself.
To also show you the lines before your matches, you can add -B to your grep. The -B 4 tells grep to also show the 4 lines before the match. Alternatively, to show the log lines that match after the keyword, use the -A parameter. In this example, it will tell grep to also show the 2 lines after the match.
grep's -A 1
option will give you one line after; -B 1
will give you one line before; and -C 1
combines both to give you one line both before and after, -1
does the same.
Use -B, -A or -C option
grep --help ... -B, --before-context=NUM print NUM lines of leading context -A, --after-context=NUM print NUM lines of trailing context -C, --context=NUM print NUM lines of output context -NUM same as --context=NUM ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With