0

Need to shift the last VirtualHost string in a file at eof. I tried using sed

#!/bin/bash
tac infile.txt | sed "s/<\/VirtualHost>//; ta ; b ; :a ; N ; ba" | tac
echo "</VirtualHost>" >>infile.txt

Current Text:

</VirtualHost>
#Added for Patch 
<LocationMatch ^/bea_wls_internal/>
RewriteEngine ON
</VirtualHost>
RewriteOptions inherit
</LocationMatch>

Desired Text:

</VirtualHost>
#Added for Patch 
<LocationMatch ^/bea_wls_internal/>
RewriteEngine ON
RewriteOptions inherit
</LocationMatch>
</VirtualHost> 
4

5 回答 5

1

在这种ed情况下,编辑器会派上用场。它在调用时将自己定位在文件的最后一行,因此您需要做的就是向后搜索所需的行并将其删除。您也可以轻松地添加回该行(首先这样做很有意义):

echo 'a
</VirutalHost>
.
?</VirtualHost>?
d
wq' | ed -s infile.txt

-s选项抑制ed的诊断输出。

a追加到仅包含的行.

?向后搜索

d删除一行

wq写入文件并退出

于 2013-09-25T13:41:49.320 回答
0

这可能对您有用(GNU sed):

sed -r '\|^</VirtualHost>|{x;/./p;d};x;/./!{x;b};x;H;$!d;x;s/^([^\n]*)\n(.*)/\2\n\1/' file
于 2013-09-25T15:01:11.567 回答
0
$ awk -v str="</VirtualHost>" 'NR==FNR {if (index($0,str)) skip=FNR; next} FNR!=skip; END{print str}' file file
</VirtualHost>
#Added for Patch 
<LocationMatch ^/bea_wls_internal/>
RewriteEngine ON
RewriteOptions inherit
</LocationMatch>
</VirtualHost>
于 2013-09-25T18:18:37.510 回答
0

呆呆的

awk -v RS='/VirtualHost>\n' 'RT{printf prevRT; printf $0; prevRT=RT};
!RT{printf $0prevRT}' file
于 2013-09-26T03:39:23.290 回答
0

您的命令有效:

#!/bin/bash
tac infile.txt | sed "s/<\/VirtualHost>//; ta ; b ; :a ; N ; ba" | tac
echo "</VirtualHost>" >>infile.txt

评论

我正在使用的 tac 语句能够在控制台上正确打印所需的输出,但是如何在文件中进行这些更改?

为此,请注意我添加的更改。它们包括将结果保存到临时文件中new_file,然后将其移动到infile.txt.

#!/bin/bash
tac infile.txt | sed "s/<\/VirtualHost>//; ta ; b ; :a ; N ; ba" | tac > new_file
echo "</VirtualHost>" >> new_file
mv new_file infile.txt
于 2013-09-25T13:50:54.120 回答