有一个包含重复注释行的文件,例如:
# ScriptAlias /cgi-bin/ "somepath"
# ScriptAlias /cgi-bin/ "otherpath"
我只想在最后一次出现之后添加一行
# ScriptAlias /cgi-bin/ "somepath"
# ScriptAlias /cgi-bin/ "otherpath"
ScriptAlias /cgi-bin/ "mypath"
为此,我使用以下命令:
sed -i 's:^\(.*ScriptAlias /cgi-bin/.*\):\1 \nScriptAlias /cgi-bin/ "mypath":' file
但这会导致每次出现后添加我的行,例如:
# ScriptAlias /cgi-bin/ "somepath"
ScriptAlias /cgi-bin/ "mypath"
# ScriptAlias /cgi-bin/ "otherpath"
ScriptAlias /cgi-bin/ "mypath"
我如何告诉 sed 仅替换最后一个出现的位置?
EDITED:
如果无法使用 sed 解决它(如评论中所述),请提供达到相同结果的替代方案,谢谢。
EDITED:
重复的行可以分开,并且它们之间可以有其他行,例如
# ScriptAlias /cgi-bin/ "somepath"
# ScriptAlias /cgi-bin/ "otherpath"
# ScriptAlias /cgi-bin/ "another-path"
ScriptAlias /foo/ "just-jump"
# ScriptAlias /cgi-bin/ "that's the last"
Use tac http://man.cx/tac所以你打印你的新行first当你看到这个模式的时候:
tac file | awk '/ScriptAlias/ && ! seen {print "new line"; seen=1} {print}' | tac
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)