mb47 mb47 - 6 months ago 10
Bash Question

How can I display 4 lines above the matched pattern

Here's the file temp.file

Line no1
Line no2
Line no3
Line no4
Line no5
abc


I am using
less temp.file|grep -i "abc"

which prints me the line "abc".

But I want the 4 lines above it to be printed as well..

So, the desired output should be

Line no2
Line no3
Line no4
Line no5
abc


How, can I get that.

Answer

There is an option for that in GNU grep: -B

less temp.file | grep  -B4 -i "abc"

From the Man-Page on 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.

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