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?
14 Answers
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.
ack works with similar arguments as grep, and accepts -C
. But it's usually better for searching through code.
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
ripgrep
If you care about the performance, use ripgrep
which has similar syntax to grep
, e.g.
rg -C5 "pattern" .
-C
,--context NUM
- Show NUM lines before and after each match.
There are also parameters such as -A
/--after-context
and -B
/--before-context
.
The tool is built on top of Rust's regex engine which makes it very efficient on the large data.
Search for "17655" in "/some/file.txt" showing 10 lines context before and after (using Awk), output preceded with line number followed by a colon. Use this on Solaris when 'grep' does not support the "-[ACB]" options.
awk '
/17655/ {
for (i = (b + 1) % 10; i != b; i = (i + 1) % 10) {
print before[i]
}
print (NR ":" ($0))
a = 10
}
a-- > 0 {
print (NR ":" ($0))
}
{
before[b] = (NR ":" ($0))
b = (b + 1) % 10
}' /some/file.txt;
Here is the @Ygor solution in awk
awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=3 a=3 s="pattern" myfile
Note: Replace a
and b
variables with number of lines before and after.
It's especially useful for system which doesn't support grep's -A
, -B
and -C
parameters.
If you search code often, AG the silver searcher is much more efficient (ie faster) than grep.
You show context lines by using -C option.
Eg:
ag -C 3 "foo" myFile
line 1
line 2
line 3
line that has "foo"
line 5
line 6
line 7
man grep | grep -C 1 context
:) – StvnWman grep | grep -C 1 "\-C"
;) – Anders B