有 sed 替换字符串但跳过第一次出现 [英] Have sed make substitute on string but SKIP first occurrence

查看:88
本文介绍了有 sed 替换字符串但跳过第一次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经历过 sed one liners 但我的目标仍然有问题.我想在除第一次出现的行之外的所有地方替换匹配的字符串.我的确切用法是:

I have been through the sed one liners but am still having trouble with my goal. I want to substitue matching strings on all but the first occurrence of a line. My exact usage would be:

 $ echo 'cd /Users/joeuser/bump bonding/initial trials' | sed <<MAGIC HAPPENS>
 cd /Users/joeuser/bump\ bonding/initial\ trials

该行将 bump bonding 中的空格替换为斜杠空格 bump\bonding 以便我可以执行此行(因为当空格没有转义时,我不会不能 cd 到它).

The line replaced the space in bump bonding with the slash space bump\ bonding so that I can execute this line (since when the spaces aren't escaped I wouldn't be able to cd to it).

更新:我通过使用单引号和输出解决了这个问题

Update: I solved this by just using single quotes and outputting

 cd 'blah blah/thing/another space/'

然后使用 source 执行命令.但它没有回答我的问题.不过我还是很好奇……你会如何使用 sed 来修复它?

and then using source to execute the command. But it didn't answer my question. I'm still curious though... how would you use sed to fix it?

推荐答案

gn 可以避免这个问题

You can avoid the problem with g and n

全部替换,然后撤消第一个:

Replace all of them, then undo the first one:

sed -e 's/ /\\ /g' -e 's/\\ / /1'

这是另一种使用 t 分支如果替换命令的方法:

Here's another method which uses the t branch-if-substituted command:

sed ':a;s/\([^ ]* .*[^\\]\) \(.*\)/\1\\ \2/;ta'

它的优点是可以完整地保留输入中现有的反斜杠空间序列.

which has the advantage of leaving existing backslash-space sequences in the input intact.

这篇关于有 sed 替换字符串但跳过第一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆