How do i grep one line before and after a matching pattern in a file?



  • Man page for grep: https://www.lightnetics.com/post/3317

    The contents of the file (named grepfile) is:

    $ cat grepfile
    apples
    pears
    This is the first block
    oranges
    plums
    
    apples
    pears
    This is the second block
    oranges
    plums
    
    apples
    pears
    This is the third block
    oranges
    plums
    

    The -A and -B options as per the man page.

    Context Line Control
           -A NUM, --after-context=NUM
    	      Print  NUM  lines  of  trailing  context	after  matching lines.
    	      Places  a  line  containing  a  group  separator	(--)   between
    	      contiguous  groups  of  matches.	With the -o or --only-matching
    	      option, this has no effect and a warning is given.
    
           -B NUM, --before-context=NUM
    	      Print NUM  lines	of  leading  context  before  matching	lines.
    	      Places   a  line	containing  a  group  separator  (--)  between
    	      contiguous groups of matches.  With the  -o  or  --only-matching
    	      option, this has no effect and a warning is given.
    

    My search string is block.

    $ grep -A 1 -B 1 block grepfile
    pears
    This is the first block
    oranges
    --
    pears
    This is the second block
    oranges
    --
    pears
    This is the third block
    oranges
    

    The before and after -A & -B values can be different. If you just a consistent number before and after you can also use -C

    -C NUM, -NUM, --context=NUM
    	      Print  NUM  lines of output context.  Places a line containing a
    	      group separator (--) between contiguous groups of matches.  With
    	      the  -o  or  --only-matching  option,  this  has no effect and a
    	      warning is given.
    
    $ grep -C 1 block grepfile
    pears
    This is the first block
    oranges
    --
    pears
    This is the second block
    oranges
    --
    pears
    This is the third block
    oranges
    


© Lightnetics 2024