Delete range of lines above pattern

By | 2019-01-11

Displaying lines (eg: 2 lines) above pattern is easy with grep -B2 option. The ‘-v’ option removes only the matched lines but it not working with -B2 option. Option “-B” print outs lines, not select them.

From manual of grep:

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

sed can suppress more lines, but only after the pattern:

sed -n '/pattern/{n;n;d;}; p' <file

So we have print out the content of file in reverse order, suppress the pattern and the following n lines, then reverse it back.

tac file | sed '/pattern/I,+n d' | tac

Example: Remove “4444” and 2 lines above the pattern from file called “file”. Content of “file”:

1111
2222
3333
4444
5555
6666
7777
8888
9999
1111
2222
3333
4444
5555
6666
7777
8888
9999

Command:

tac file | sed '/4444/I,+2 d' | tac

Output:

1111
5555
6666
7777
8888
9999
1111
5555
6666
7777
8888
9999

For more details please check https://unix.stackexchange.com/questions/29906/delete-range-of-lines-above-pattern-with-sed-or-awk .