我已经通过了sed one liners但我的目标仍然有问题.除了第一次出现一行之外,我想替换匹配的字符串.我的确切用法是:
$ echo 'cd /Users/joeuser/bump bonding/initial trials' | sed <<MAGIC HAPPENS>
cd /Users/joeuser/bump\ bonding/initial\ trials
Run Code Online (Sandbox Code Playgroud)
该行用bump bonding斜杠空格替换了空格,bump\ bonding以便我可以执行这一行(因为当空格没有被转义时,我将无法cd到它).
更新:我通过使用单引号和输出解决了这个问题
cd 'blah blah/thing/another space/'
Run Code Online (Sandbox Code Playgroud)
然后source用来执行命令.但它没有回答我的问题.我仍然很好奇......你会怎么用sed它来解决它?
Pau*_*ce. 12
你可以避免g和n的问题
替换所有这些,然后撤消第一个:
sed -e 's/ /\\ /g' -e 's/\\ / /1'
Run Code Online (Sandbox Code Playgroud)
这是另一种使用tbranch-if-substituted命令的方法:
sed ':a;s/\([^ ]* .*[^\\]\) \(.*\)/\1\\ \2/;ta'
Run Code Online (Sandbox Code Playgroud)
这样做的好处是可以在输入中保留现有的反斜杠空间序列.
s/ /\\ /2g
Run Code Online (Sandbox Code Playgroud)
在2这第二个应该申请指定,而g所有剩下的应该施加太大指定.(这可能仅适用于GNU sed.根据Open Group Base Specification," 如果指定了g和n,则结果未指定. ")