Joe User Joe User - 1 month ago 14
Bash Question

awk: delete lines in specific block of text

This time i search for an extended version of the second awk-oneliner from the accepted answer to my question 40066030, so please have a look there first, thanks.

This awk has to be extended so i can delete all lines containing the word foobar from the same block number (num) before i insert the file inserted.txt into it:

/usr/bin/awk -v num=2 'NR==FNR{ins=ins?ins ORS $0:$0; next} /<\/VirtualHost>/ && ++c==num{print ins} 1' inserted.txt vhosts-ssl.conf


Output of previous awk:

$ cat vhosts-ssl.conf
<VirtualHost *:443>
vhost 1
foobar 1
foobar 2
barfoo 1
barfoo 2
</VirtualHost>

<VirtualHost *:443>
vhost 2
foobar 2
barfoo 1
foobar 1
barfoo 2
inserted line 1
inserted line 2
</VirtualHost>
<VirtualHost *:443>
vhost 3
foobar 1

barfoo 1
foobar 2

barfoo 2
</VirtualHost>

<VirtualHost *:443>

vhost 4
foobar 1
foobar 2

barfoo 1
barfoo 2

</VirtualHost>


Output i need to get:

$ cat vhosts-ssl.conf
<VirtualHost *:443>
vhost 1
foobar 1
foobar 2
barfoo 1
barfoo 2
</VirtualHost>

<VirtualHost *:443>
vhost 2
barfoo 1
barfoo 2
inserted line 1
inserted line 2
</VirtualHost>
<VirtualHost *:443>
vhost 3
foobar 1

barfoo 1
foobar 2

barfoo 2
</VirtualHost>

<VirtualHost *:443>

vhost 4
foobar 1
foobar 2

barfoo 1
barfoo 2

</VirtualHost>


Original input data for reference:

$ cat inserted.txt
inserted line 1
inserted line 2
$ cat vhosts-ssl.conf
<VirtualHost *:443>
vhost 1
foobar 1
foobar 2
barfoo 1
barfoo 2
</VirtualHost>

<VirtualHost *:443>
vhost 2
foobar 2
barfoo 1
foobar 1
barfoo 2
</VirtualHost>
<VirtualHost *:443>
vhost 3
foobar 1

barfoo 1
foobar 2

barfoo 2
</VirtualHost>

<VirtualHost *:443>

vhost 4
foobar 1
foobar 2

barfoo 1
barfoo 2

</VirtualHost>


I tried to insert various seach&replace and delete snippets right before the print, but that didn't work (stupid me) :( Something like that:

/usr/bin/awk -v num=2 'NR==FNR{ins=ins?ins ORS $0:$0; next} /<\/VirtualHost>/ && ++c==num{!/foobar/ print ins} 1' inserted.txt vhosts-ssl.conf


Thanks in advance.

Answer

You have to modify the script slightly as such

$ awk -v num=2     'NR==FNR{ins=ins?ins ORS $0:$0; next} 
   /<VirtualHost/&&++c==num{p=1} 
       p&&/<\/VirtualHost>/{print ins; p=0} 
              !p||!/foobar/' insert.file orig.file
Comments