Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove previous line to a match string?

Tags:

bash

sed

How I can remove the previous line of a match pattern?

Or

the opposite of:

sed -n '/pattern/{g;1!p;};h'
like image 398
Canna Avatar asked May 03 '26 15:05

Canna


2 Answers

Use tac | sed | tac (Linux/Solaris) then it's next line after a match pattern :)

like image 107
Cyrus Avatar answered May 05 '26 11:05

Cyrus


sed is an excellent tool for simple substitutions on a single line, for anything else just use awk:

$ cat file
here is a
a bad line before
a good line
in a file

$ awk 'NR==FNR{if (/good/) del[NR-1]; next} !(FNR in del)' file file
here is a
a good line
in a file

You can use the above idiom to delete any number of lines before and/or after a given pattern, e.g. to delete the 3 lines before and 2 lines after a given target:

$ cat file
-5
-4
-3
-2
-1
target
+1
+2
+3
+4
+5
$
$ awk 'NR==FNR{if (/target/) for (i=-3;i<=2;i++) del[NR+i]; next} !(FNR in del)' file file
-5
-4
+3
+4
+5

or to leave the target in place and just delete the lines around it:

$ awk 'NR==FNR{if (/target/) for (i=-3;i<=2;i++) if (i!=0) del[NR+i]; next} !(FNR in del)' file file
-5
-4
target
+3
+4
+5

All very clear, trivial, and scalable...

like image 30
Ed Morton Avatar answered May 05 '26 10:05

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!