usergg123
usergg123

Reputation: 37

Sed to search regex pattern and remove line with above pattern

this is my file.txt content. Here I'm trying to search pattern text: 'About' and remove items:[{ line with the command as below:

file.txt:

                items: [{
                        text: 'About',
                        handler: function() { TP.aboutWindow() }

Command: sed -n -i -E '/text\: \'About\'/{n; $p; x; d}; x; 1!p; ${x;p;}' file.txt

but it seems to be not working. Is there any way to make it work to remove line above pattern?

Thanks in advance.

Upvotes: 3

Views: 851

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You can use

sed -i "N;/\n.*text: 'About'/"'!P;D' file.txt

Details:

  • -i - file inplace replacement mode on
  • N - opens a two-line window throughout the whole file (it reads the next line prepended with a newline into pattern space)
  • \n.*text: 'About' matches a newline, then any text and then text: 'About'
  • !P;D - if there is a match, do not print the first line, then delete the first line and repeat.

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133428

In case you are ok with awk, could you please try following with awk + tac combination here. This will print the output on terminal, once you are happy with results you can append > temp && mv temp Input_file at last of following command too.

tac Input_file | 
awk '
found && /items:/{
  found=""
  next
}
/text: \047About\047/{
  found=1
}
1' | 
tac

Upvotes: 3

Related Questions