How I can remove the previous line of a match pattern?
Or
the opposite of:
sed -n '/pattern/{g;1!p;};h'
Use tac | sed | tac (Linux/Solaris) then it's next line after a match pattern :)
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With