【发布时间】:2012-04-23 18:41:37
【问题描述】:
有一个包含重复注释行的文件,例如:
# 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 只替换最后一次出现的内容?
已编辑:
如果无法使用 sed 解决它(如 cmets 中所述),请提供达到相同结果的替代方法,谢谢。
已编辑:
重复的行可以分开,并且可以在它们之间使用其他行,例如
# ScriptAlias /cgi-bin/ "somepath"
# ScriptAlias /cgi-bin/ "otherpath"
# ScriptAlias /cgi-bin/ "another-path"
ScriptAlias /foo/ "just-jump"
# ScriptAlias /cgi-bin/ "that's the last"
【问题讨论】:
-
这不是 sed 的工作。也许是 awk,但我会用 Python 或 Perl 来做。
-
@MK.Ok .. 我要求 sed 因为我正在使用它。如果无法使用 sed 解决它,欢迎使用任何其他方法。谢谢
-
哦,你可以用 sed 做到这一点,在我看来这并不理想。
标签: bash replace sed awk last-occurrence