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
grep -C 3 foo README.txt
This will show 3 lines before and 3 lines after.
In other words,
-B will work, as will
-C n (for
n lines of context), or just
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.
Many GNU tools also have an info page that may have more useful information in addition to the man page.
Print N lines after matching lines
You can use
-A n option to print N lines after matching lines.
$ 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
-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
-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?
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
\n to match the newline and by telling
grep the file is null separated with
$ grep -zPo 'This is a sweet\nlemon' file_type This is a sweet lemon.
-EUse extended regular expressions (to use
|character for alternation without needing to escape it)
-AnPrint additional lines after the pattern, where n is the number of trailing lines to print
-PUse perl-style regular expressions (“experimental” in
pcregrepinstead for better perl regex support)
-zUse the null character as separator (just pretending in this case, but
grepwill take our word for it)
-oonly print the matched part
Hope you learned something from this post.
Follow Programming Articles for more!