Luc*_*one 5 bash awk replace sed last-occurrence
拥有包含重复注释行的文件,例如:
# ScriptAlias /cgi-bin/ "somepath"
# ScriptAlias /cgi-bin/ "otherpath"
Run Code Online (Sandbox Code Playgroud)
我想在最后一次出现之后添加一行
# ScriptAlias /cgi-bin/ "somepath"
# ScriptAlias /cgi-bin/ "otherpath"
ScriptAlias /cgi-bin/ "mypath"
Run Code Online (Sandbox Code Playgroud)
为此,我正在使用此命令:
sed -i 's:^\(.*ScriptAlias /cgi-bin/.*\):\1 \nScriptAlias /cgi-bin/ "mypath":' file
Run Code Online (Sandbox Code Playgroud)
但这导致在每次出现后添加我的线条,如:
# ScriptAlias /cgi-bin/ "somepath"
ScriptAlias /cgi-bin/ "mypath"
# ScriptAlias /cgi-bin/ "otherpath"
ScriptAlias /cgi-bin/ "mypath"
Run Code Online (Sandbox Code Playgroud)
我怎么能告诉sed只替换最后一次出现?
编辑:
如果没有办法用sed解决它(如评论中所述),请提供相同结果的替代方案,谢谢.
编辑:
重复的线条可以分开,并且它们之间有其他线条
# ScriptAlias /cgi-bin/ "somepath"
# ScriptAlias /cgi-bin/ "otherpath"
# ScriptAlias /cgi-bin/ "another-path"
ScriptAlias /foo/ "just-jump"
# ScriptAlias /cgi-bin/ "that's the last"
Run Code Online (Sandbox Code Playgroud)
使用tac,以便在第一次看到模式时打印新行:
tac file | awk '/ScriptAlias/ && ! seen {print "new line"; seen=1} {print}' | tac
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5620 次 |
| 最近记录: |