awk:删除特定文本块中的行

时间:2016-10-19 18:22:43

标签: shell unix awk freebsd

这次我从我的question 40066030接受的答案中搜索第二个awk-oneliner的扩展版本,所以请先看一下,谢谢。

这个awk必须被扩展,所以我可以删除包含单词foobar的所有行来自相同的块号(num),然后将insert.txt文件插入其中:

/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

以前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>

输出我需要得到:

$ 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>

原始输入数据供参考:

$ 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>

我试图在打印之前插入各种搜索和替换以及删除片段,但这不起作用(愚蠢的我):(类似的东西:

/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

提前致谢。

1 个答案:

答案 0 :(得分:1)

您必须稍微修改脚本

$ 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