3668

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?

alexyorke
  • 4,083
  • 3
  • 32
  • 54
Mark Harrison
  • 267,774
  • 112
  • 308
  • 434
  • 6
    For a solution that works on Solaris, check out [this link](http://www.unix.com/solaris/33533-grep-display-few-lines-before-after.html). – jahroy May 30 '13 at 22:55
  • 3
    I keep a copy of [Brendan Gregg's perl script](http://www.brendangregg.com/Perl/search) around for this purpose. Works well. – Ethan Post Sep 04 '08 at 19:16
  • 121
    `man grep | grep -C 1 context` :) – StvnW Nov 03 '15 at 03:57
  • 21
    `man grep | grep -C 1 "\-C"` ;) – Anders B Jul 07 '16 at 10:56
  • 11
    @StvnW ... I don't know whether to call that [meta](https://en.wiktionary.org/wiki/meta#Adjective) (in a more general, rather than SO context), or what to call it. You answered the question by showing how to use the answer to find the answer. – bballdave025 Sep 14 '18 at 20:50
  • Perhaps someone [elsewhere in StackExchange](https://english.stackexchange.com/q/464362/300794) can give us an answer. – bballdave025 Sep 14 '18 at 21:45

14 Answers14

4878

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.

Vladyslav
  • 1,752
  • 4
  • 15
  • 38
Pat Notz
  • 186,044
  • 29
  • 86
  • 92
  • 57
    It is good but unfortunately the Solaris grep does not support that. See that link for solaris: http://www.unix.com/solaris/33533-grep-display-few-lines-before-after.html – рüффп Mar 21 '11 at 12:55
  • 9
    Ok, but what if want to show _all_ lines of output after the match? grep -A0 and grep -A-1 don't cut it... – g33kz0r Jul 22 '11 at 02:18
  • ruffp: I believe there is also GNUgrep – Mailo Světel Feb 24 '12 at 18:53
  • 2
    does not work for me for some reason, although mentioned in my man pages. – Hayri Uğur Koltuk Aug 01 '12 at 09:43
  • 2
    If you are HP-UX env, none of the grep versions will work like in Solaris. Was able to use the Solaris link but replace nawk with awk in that link. – zkarthik Jan 23 '13 at 21:45
  • 6
    -n is for line numbers, but for some versions of grep -n# will show # surrounding lines (like -c) with line numbers. That's a useful shortcut that's my go-to when I need context. – Anthony DiSanti May 07 '13 at 16:24
  • 2
    @g33kz0r, in that case you should ask in a separate question. (Even though someone took the trouble to answer you here, beats me why...) – alexis Oct 01 '14 at 16:02
  • Solaris grep does not support this. But gnu grep supports Solaris. – guettli Jun 12 '15 at 15:08
  • 1
    This works on "Bash on Ubunutu on Windows" as well! The Windows subsystem for Linux uses Ubuntu 14.04.4 LTS as of this writing. – Adam Venezia Jul 15 '16 at 17:13
  • @g33kz0r Do a wc -l on the file, and make that your -A value. Then you know it will display all lines in your file after the match – Goldfish Nov 15 '18 at 20:04
  • zOS grep uses a different flag for leading context: `-P` instead of _-B_. – Stavr00 Oct 01 '19 at 18:15
  • whoever made this command line is a genius. – GeneCode May 05 '21 at 03:16
  • Hahaha, `-A` and `-B` it is bad flag, dont it? I first thought it was `above` and `below`, which is the opposite of `after` and `before`! – André May 06 '21 at 18:11
623

-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).

Trevor Boyd Smith
  • 15,512
  • 24
  • 110
  • 159
Stu
  • 14,881
  • 4
  • 37
  • 73
  • 1
    I tried the `-n` format and found out it only works till `9`. For `15` it returns 5 lines – Deepak Mahakale Mar 27 '19 at 07:49
  • 11
    @DeepakMahakale This is probably related to how command-line arguments / options are typically parsed by POSIX programs. The option specifier is a single character (such as `-A`, `-B` or `-C`). Usually, the option specifier is followed by a value (`-o a.out` to specify output file in GCC), but it can also function as a simple switch / flag (`-g` to enable debugging info in GCC). However spaces between options are optional, so for options without a value, it is possible to merge them (`-ABC`), which means that `-15` is interpreted `-1 -5` (two separate options) and the `-5` overrides the `-1`. – natiiix Apr 19 '19 at 12:17
  • 1
    -5 is quicker than both -A 5 -B 5. Those are not meant to be used together. It is cleaner to other readers of the script if you choose -A or -B or -C over -9. – Eric Aldinger Jun 07 '19 at 17:01
79

ack works with similar arguments as grep, and accepts -C. But it's usually better for searching through code.

Andy Lester
  • 81,480
  • 12
  • 93
  • 144
elmarco
  • 27,816
  • 21
  • 58
  • 68
  • 5
    ack also supports -A -B. – Shuo Nov 04 '16 at 07:49
  • Ack is better than grep in many ways. It's faster with a simpler syntax. – chim Feb 07 '17 at 10:30
  • 1
    grep has the advantage of being installed by default on many systems though. – Marc Z Oct 16 '18 at 10:49
  • 1
    @MarcZ: True, grep is more likely to be installed by default than ack, but ack is a portable, stand-alone script. There's no need to compile it or install it in a system directory such as /usr/bin/. Once it's downloaded and placed into a directory listed in the $PATH (and its eXecute permission bit set), it should work right away. (No sudo or root privileges are required to get ack to work.) – J-L Nov 12 '18 at 17:41
  • This question is about `grep`, not sure using it to "advertise" `ack` (which is a great tool, indeed) is a good idea… – MonsieurDart Dec 10 '19 at 14:24
40
grep astring myfile -A 5 -B 5

That will grep "myfile" for "astring", and show 5 lines before and after each match

dbr
  • 153,498
  • 65
  • 266
  • 333
20

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
Csa77
  • 449
  • 9
  • 17
Sam Merrell
  • 2,322
  • 2
  • 16
  • 14
16

Use grep

$ grep --help | grep -i context
Context control:
  -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
Chiel ten Brinke
  • 12,091
  • 12
  • 60
  • 104
  • Did you not read the accepted answer? You are just repeating what has already been said on a question almost 10 years old... – Yokai Jan 13 '18 at 09:22
  • 8
    Oh I'm sorry Yokai. But I don't read anything about grepping the help section of grep to retrieve the answer. – Chiel ten Brinke Jan 13 '18 at 10:30
  • 1
    @Yokai Besides what Chiel ten Brinke said, the accepted answer does not mention the long options – user3738870 Sep 13 '19 at 19:57
12

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;
Kent Pawar
  • 1,488
  • 2
  • 17
  • 33
Malcolm Boekhoff
  • 862
  • 10
  • 7
10

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.

kenorb
  • 118,428
  • 63
  • 588
  • 624
5

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.

kenorb
  • 118,428
  • 63
  • 588
  • 624
4
$ grep thestring thefile -5

-5 gets you 5 lines above and below the match 'thestring' is equivalent to -C 5 or -A 5 -B 5.

kenorb
  • 118,428
  • 63
  • 588
  • 624
JBone
  • 1,176
  • 2
  • 13
  • 25
4

Grep has an option called Context Line Control, you can use the --context in that, simply,

| grep -C 5

or

| grep -5

Should do the trick

Noctis
  • 10,865
  • 3
  • 38
  • 74
prime
  • 11,246
  • 11
  • 75
  • 112
1

I use to do the compact way

grep -5 string file

That is the equivalent of

grep -A 5 -B 5 string file
franzisk
  • 1,404
  • 11
  • 17
1

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
Rose
  • 2,382
  • 3
  • 23
  • 38
1

You can use option -A (after) and -B (before) in your grep command try grep -nri -A 5 -B 5 .

Issam.Chorfa
  • 49
  • 2
  • 12