Bash:如何使用sed只替换文件中的最后一次出现?
发布时间:2020-12-15 21:15:35 所属栏目:安全 来源:网络整理
导读:拥有包含重复注释行的文件,例如: # ScriptAlias /cgi-bin/ "somepath"# ScriptAlias /cgi-bin/ "otherpath" 我想在最后一次出现之后添加一行 # ScriptAlias /cgi-bin/ "somepath"# ScriptAlias /cgi-bin/ "otherpath"ScriptAlias /cgi-bin/ "mypath" 为此,
拥有包含重复注释行的文件,例如:
# 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只替换最后一次出现? 编辑: 编辑: # 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,以便在第一次看到模式时打印新行:
tac file | awk '/ScriptAlias/ && ! seen {print "new line"; seen=1} {print}' | tac (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |