【发布时间】:2017-02-25 05:39:21
【问题描述】:
有两个文件,第一个是 Apache 配置文件:
$ 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>
第二个文件包含应该添加到一个(变量)特定 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
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>
我尝试了以下 sed 的一些变体,但没有成功:
$ sed -e '/^<VirtualHost/{:a;n;/^<\/VirtualHost/\!ba;r inserted.txt' -e '}' vhosts-ssl.conf
我无法弄清楚如何只选择一个我需要将文件插入到的 VirtualHost 块,并且由于我必须使用 FreeBSD sed(或 awk),所以我在使用之前的 sed 命令时也会收到此错误:
$ sed -e '/^<VirtualHost/{:a;n;/^<\/VirtualHost/\!ba;r inserted.txt' -e '}' vhosts-ssl.conf
sed: 2: "}
": unused label 'a;n;/^<\/VirtualHost/!ba;r inserted.txt'
使用 GNU sed 我得到这个输出:
$ gsed -e '/^<VirtualHost/{:a;n;/^<\/VirtualHost/\!ba;r inserted.txt' -e '}' vhosts-ssl.conf
<VirtualHost *:443>
vhost 1
foobar 1
foobar 2
barfoo 1
barfoo 2
</VirtualHost>
inserted line 1
inserted line 2
<VirtualHost *:443>
vhost 2
foobar 2
barfoo 1
foobar 1
barfoo 2
</VirtualHost>
inserted line 1
inserted line 2
<VirtualHost *:443>
vhost 3
foobar 1
barfoo 1
foobar 2
barfoo 2
</VirtualHost>
inserted line 1
inserted line 2
<VirtualHost *:443>
vhost 4
foobar 1
foobar 2
barfoo 1
barfoo 2
</VirtualHost>
inserted line 1
inserted line 2
由于我想了解我的错误并从中吸取教训,我希望得到一些解释的答案,甚至可能是一些指向 rtfm 的链接,谢谢。
添加于 2016 年 10 月 16 日
伪代码:
if BLOCK begins with /^<VirtualHost/
and ends with /^<\/VirtualHost/
and is the ${n-th} BLOCK
in FILE_1
then insert content of FILE_2
before last line of ${n-th} BLOCK
without touching rest of FILE_1
endif
save modified FILE_1
${n-th} 由以下人员收集:
$ httpd -t -D DUMP_VHOSTS | \
grep -i "${SUBDOMAIN}.${DOMAIN}" | \
awk '/^[^\ ]*:443[\ ]*/ {print $3}' | \
sed -e 's|(\(.*\))|\1|' | \
cut -d: -f2
输出是我想通过 FILE_2 扩展的 BLOCK 的编号
请只使用非 GNU 版本,因为我在 FreeBSD 上,谢谢。
【问题讨论】:
-
我添加了一些伪代码
标签: shell unix awk sed freebsd