-1

Trying to delete 4 lines in a file. First want to delete the Pattern matched line, along with it also need to delete 3 lines before the pattern match.

Eg:
1.land service=bus
2.land service=car
3.land service=truck
4.land service=cycle
5.
6.air service=plane
7.air service=rocket

My pattern match is in line 6. (i.e: air service=plane) based on that i need to delete line's 6,5,4,and 3.

My output looks like.
1.land service=bus
2.land service=car
3.air service=rocket

Tried the below code: grep -B2 'air service=plane' pattern.txt | sed -n '1,3p'

i am trying to use sed and awk to delete these lines in a file, could you please advise the best method to do so.

2 Answers2

2

One option is using tac and sed like this:

tac file | sed '/air service=plane/,+3d' | tac

To save changes, use a temporary file:

tac file | sed '/air service=plane/,+3d' | tac > tmpfile && mv tmpfile file
oguz ismail
  • 1
  • 16
  • 47
  • 69
0

try this:

tac yourfile.txt | sed "/air service=plane/{N;N;N;d}" | tac

explanation:

tac yourfile.txt               # reverse file

sed "/air service=plane/       # find pattern
{N;N;N;d}"                     # concatenate next 3 lines (N) and delete (d)

tac                            # reverse output

output

1.land service=bus
2.land service=car
7.air service=rocket
UtLox
  • 3,744
  • 2
  • 10
  • 13