Bash:如何使用sed仅替换文件中的最后一次出现? [英] Bash: how to use sed to replace only the last occurence in a file?
问题描述
具有包含重复的注释行的文件,例如:
Having a file containing repeated commented lines like:
# ScriptAlias /cgi-bin/ "somepath"
# ScriptAlias /cgi-bin/ "otherpath"
我只想在最后一次出现后添加一行
I want to add a line only after the last occurence resulting in
# ScriptAlias /cgi-bin/ "somepath"
# ScriptAlias /cgi-bin/ "otherpath"
ScriptAlias /cgi-bin/ "mypath"
为此,我正在使用以下命令:
To do so I'm using this command:
sed -i 's:^\(.*ScriptAlias /cgi-bin/.*\):\1 \nScriptAlias /cgi-bin/ "mypath":' file
但这会导致每次出现后添加我的行,例如:
But this results in adding my line after each occurence like:
# ScriptAlias /cgi-bin/ "somepath"
ScriptAlias /cgi-bin/ "mypath"
# ScriptAlias /cgi-bin/ "otherpath"
ScriptAlias /cgi-bin/ "mypath"
我如何告诉sed仅替换最后一次出现的事件?
已编辑:
如果没有办法使用sed来解决它(如评论中所述),请提供达到相同结果的替代方法,谢谢.
How can I tell sed to replace only the last occurence?
EDITED:
If there's no way to solve it using sed (as said in comments), please provide alternatives reaching the same result, thanks.
已编辑:
重复的行可以分开,并且它们之间可以有其他行
EDITED:
The repeated lines can be separeted and with other lines between them like
# ScriptAlias /cgi-bin/ "somepath"
# ScriptAlias /cgi-bin/ "otherpath"
# ScriptAlias /cgi-bin/ "another-path"
ScriptAlias /foo/ "just-jump"
# ScriptAlias /cgi-bin/ "that's the last"
推荐答案
使用 tac ,以便先在上打印新行当您看到模式时:
Use tac so you print your new line the first time you see the pattern:
tac file | awk '/ScriptAlias/ && ! seen {print "new line"; seen=1} {print}' | tac
这篇关于Bash:如何使用sed仅替换文件中的最后一次出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!