Query:
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?
grep a file, but show several surrounding lines:
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.
In other words,
-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).
I normally use
grep searchstring file -C n # n for number of lines of context up and down
Many of the tools like grep also have really great man files too. I find myself referring to grep’s man page a lot because there is so much you can do with it.
man grep
Many GNU tools also have an info page that may have more useful information in addition to the man page.
info grep
Answer #2:
Print N lines after matching lines
You can use grep
with -A n
option to print N lines after matching lines.
For example:
$ cat mytext.txt
Line1
Line2
Line3
Line4
Line5
Line6
Line7
Line8
Line9
Line10
$ grep -wns Line5 mytext.txt -A 2
5:Line5
6-Line6
7-Line7
Other related options:
Print N lines before matching lines
Using -B n
option you can print N lines before matching lines.
$ grep -wns Line5 mytext.txt -B 2
3-Line3
4-Line4
5:Line5
Print N lines before and after matching lines
Using -C n
option you can print N lines before and after matching lines.
$ grep -wns Line5 mytext.txt -C 2
3-Line3
4-Line4
5:Line5
6-Line6
7-Line7
How to use grep for two different lines?
To use grep
for two different lines, search for both patterns
$ grep -e sweet -e lemon file_type
This is a sweet
lemon.
Or use alternation
$ grep -E 'sweet|lemon' file_type
This is a sweet
lemon.
To get the next line after a pattern, you could use the context option
$ grep -A1 sweet file_type
This is a sweet
lemon.
But if you’re searching explicitly for a multiline pattern, that’s tricky because grep
thinks in lines…. Your .*
will catch everything between “sweet” and “lemon” on the line. We can get “lemon” on the next line with -P
using \n
to match the newline and by telling grep
the file is null separated with -z
:
$ grep -zPo 'This is a sweet\nlemon' file_type
This is a sweet
lemon.
Notes:
-E
Use extended regular expressions (to use|
character for alternation without needing to escape it)-An
Print additional lines after the pattern, where n is the number of trailing lines to print-P
Use perl-style regular expressions (“experimental” ingrep
– installpcregrep
instead for better perl regex support)-z
Use the null character as separator (just pretending in this case, butgrep
will take our word for it)-o
only print the matched part
Hope you learned something from this post.
Follow Programming Articles for more!