grep a file, but show several surrounding lines?

1,312,452

Solution 1

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.

Solution 2

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

Solution 3

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

Solution 4

grep astring myfile -A 5 -B 5

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

Solution 5

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
Share:
1,312,452
Mark Harrison
Author by

Mark Harrison

I'm a Software Engineer at Google where I work on machine learning planning systems. From 2001-2015 I was the Pixar Tech Lead of the Data Management Group. My 50-year charter was to store and catalog all data and metadata related to the Studio's feature films. This system ("Templar") is in use to this day. From 1997 to 2001 I lived in Beijing, China and was the Chief Software Architect at AsiaInfo, the company that built China's Internet. While there my software was used to grow the China Internet from 200K to 65M users. The last I heard they were at 350M+ users. I studied computer science and worked in Texas for many years. I wrote a couple of computer books... the best one was in print for 20 years. Feel free to drop me a line! [email protected]

Updated on July 08, 2022

Comments

  • Mark Harrison
    Mark Harrison almost 2 years

    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?

    • Ethan Post
      Ethan Post almost 16 years
      I keep a copy of Brendan Gregg's perl script around for this purpose. Works well.
    • jahroy
      jahroy about 11 years
      For a solution that works on Solaris, check out this link.
    • StvnW
      StvnW over 8 years
      man grep | grep -C 1 context :)
    • Anders B
      Anders B almost 8 years
      man grep | grep -C 1 "\-C" ;)
    • bballdave025
      bballdave025 almost 6 years
      @StvnW ... I don't know whether to call that meta (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
      bballdave025 almost 6 years
      Perhaps someone elsewhere in StackExchange can give us an answer.
  • рüффп
    рüффп over 13 years
    It is good but unfortunately the Solaris grep does not support that. See that link for solaris: unix.com/solaris/33533-grep-display-few-lines-before-after.h‌​tml
  • Admin
    Admin almost 13 years
    Ok, but what if want to show all lines of output after the match? grep -A0 and grep -A-1 don't cut it...
  • Mailo Světel
    Mailo Světel over 12 years
    ruffp: I believe there is also GNUgrep
  • Hayri Uğur Koltuk
    Hayri Uğur Koltuk almost 12 years
    does not work for me for some reason, although mentioned in my man pages.
  • user5403501
    user5403501 over 11 years
    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.
  • Anthony DiSanti
    Anthony DiSanti about 11 years
    -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.
  • alexis
    alexis over 9 years
    @g33kz0r, in that case you should ask in a separate question. (Even though someone took the trouble to answer you here, beats me why...)
  • guettli
    guettli about 9 years
    Solaris grep does not support this. But gnu grep supports Solaris.
  • Syed Siraj Uddin
    Syed Siraj Uddin almost 9 years
    "grep astring myfile -C 5 " will do the same
  • Adam Venezia
    Adam Venezia almost 8 years
    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.
  • Shuo
    Shuo over 7 years
    ack also supports -A -B.
  • chim
    chim over 7 years
    Ack is better than grep in many ways. It's faster with a simpler syntax.
  • Yokai
    Yokai over 6 years
    Did you not read the accepted answer? You are just repeating what has already been said on a question almost 10 years old...
  • chtenb
    chtenb over 6 years
    Oh I'm sorry Yokai. But I don't read anything about grepping the help section of grep to retrieve the answer.
  • Marc Z
    Marc Z over 5 years
    grep has the advantage of being installed by default on many systems though.
  • J-L
    J-L over 5 years
    @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.)
  • Goldfish
    Goldfish over 5 years
    @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
  • Deepak Mahakale
    Deepak Mahakale over 5 years
    I tried the -n format and found out it only works till 9. For 15 it returns 5 lines
  • natiiix
    natiiix about 5 years
    @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.
  • Eric Aldinger
    Eric Aldinger about 5 years
    -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.
  • user3738870
    user3738870 almost 5 years
    @Yokai Besides what Chiel ten Brinke said, the accepted answer does not mention the long options
  • Stavr00
    Stavr00 over 4 years
    zOS grep uses a different flag for leading context: -P instead of -B.
  • MonsieurDart
    MonsieurDart over 4 years
    This question is about grep, not sure using it to "advertise" ack (which is a great tool, indeed) is a good idea…
  • GeneCode
    GeneCode about 3 years
    whoever made this command line is a genius.
  • André
    André about 3 years
    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!
  • John Stoneman
    John Stoneman about 3 years
    Wow that's great! A = after, B = before, C = context
  • Peter Mortensen
    Peter Mortensen almost 3 years
    Why is it better for searching through code? Can you elaborate a little bit in your answer? (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today.)
  • Peter Mortensen
    Peter Mortensen almost 3 years
    On what system (incl. distribution name and version) did you try it? Was it installed by default? If not, what are some installation instructions? It is not installed by default on Ubuntu MATE 20.04 (Focal Fossa).
  • Peter Mortensen
    Peter Mortensen almost 3 years
    How is that different from the previous answers? What are the options nri supposed to do? What is actually searched for? What does it try to match? Please respond as much as possible by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
  • elmarco
    elmarco almost 3 years
    I don't think it's necessary to develop here: beyondgrep.com/why-ack. Tbh, these days I use ripgrep.
  • Janac Meena
    Janac Meena over 2 years
    Note: You can determine which grep you have using man grep. As of 2021, macOS uses BSD grep.«
  • Kajukenbo
    Kajukenbo over 2 years
    Very nice. Yes, it is more complex-looking, but it is actually cross-platform. Tested on AIX and HP-UX.
  • n_moen
    n_moen over 2 years
    @MonsieurDart A search query for "ack show lines around" brings up this SO question so this is the answer I keep coming for.
  • mchid
    mchid over 2 years
    @user67416 Use a ridiculously large number for A like -A99999999
  • mchid
    mchid over 2 years
    The -n option currently works for more than 9 lines on (GNU grep) 3.1.