I would like to grep
for a string, but also show the preceding five lines and the following five lines as well as the matched line. How would I be able to do this?
For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after.
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!
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.
To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.
For BSD or GNU grep
you can use -B num
to set how many lines before the match and -A num
for the number of lines after the match.
grep -B 3 -A 2 foo README.txt
If you want the same number of lines before and after you can use -C num
.
grep -C 3 foo README.txt
This will show 3 lines before and 3 lines after.
-A
and -B
will work, as will -C n
(for n
lines of context), or just -n
(for n
lines of context... as long as n is 1 to 9).
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