Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inplace deletion of a line before and after a pattern using sed command in linux

Tags:

shell

sed

forward-zone:
name: "."
forward-addr: 10.1.1.2

forward-zone:
name: "mydomain.com"
forward-addr: 10.1.1.1

I wanted to delete one line before the pattern 'name: "."' and one line after the pattern (including the pattern itself). I tried the following command but this is not modifying the file itself. I want to do inplace modification. Please help

sed -n '/name: "."/{N;s/.*//;x;d;};x;p;${x;p;}' file
like image 318
Suman Shil Avatar asked Nov 19 '25 02:11

Suman Shil


1 Answers

Something like this might suit.

sed -rne '/^name: "\."/{n;n;h;d};1{h;d};x;p;${g;p}' -i file

The -i option lets Sed modify the file in place. The Sed commands h, g and x use Sed's hold space to hold the previous line until the current line has been examined. The addresses 1 and $ respectively treat the file's first and last lines, which probably want special handling.

Though this has been an educational exercise, admittedly, Awk or even Perl might be a better tool than Sed for such multiline processing. Nevertheless, with some extra effort, Sed can do the job, as you see.

like image 157
thb Avatar answered Nov 21 '25 23:11

thb



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!