加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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只替换最后一次出现?

编辑:
如果没有办法用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读