2012-02-05 136 views
2

我做一个查找和使用sed替换,与BASH变量$b更换BASH变量$a(在新行的开始时):更换比赛的第一次出现使用sed

sed -i "s#^$a#$b#" ./file.txt 

这将替换^$a的所有匹配项。我怎样才能在整个文件中只替换^a的第一次出现?

+0

我使用GNU sed的版本4.2.1。 – Village 2012-02-05 03:15:45

回答

4

这应该工作:

sed -i "0,/^\$a/s//\$b/" ./file.txt 

您可以在http://www.grymoire.com/Unix/Sed.html#toc-uh-29

+1

当我尝试这个时,我得到“sed:-e表达式#1,字符3:意外','”。 – Village 2012-02-05 03:12:39

+2

你想要替换/ by#吗?按原样使用代码。 – 2012-02-05 03:29:45

+0

是的,我使用“$”而不是“/”,因为一些要被替换的项目包含“/”,但不包含任何“#”。 – Village 2012-02-05 11:15:54

1

此阅读更多有关这可能为你工作:

sed -i 'x;/^./{x;b};x;/^'"$a"'/{s//'"$b"'/;h}' file 

或者:

sed -i ':a;$!{N;ba};s/^'"$a/$b"'/m' file 
5

一你的方式唱sed

sed "s/^$var1/$var2/ ; ta ; b ; :a ; N ; ba" infile 

说明:

s/^$var1/$var2/    # Do substitution. 
ta       # If substitution succeed, go to label `:a` 
b       # Substitution failed. I still haven't found first line to 
          # change, so read next line and try again. 
:a       # Label 'a' 
N       # At this position, the substitution has been made, so begin loop 
          # where I will read every line and print until end of file. 
ba       # Go to label 'a' and repeat the loop until end of file. 

与由Jaypal提供相同的例子的试验:

含量 infile

ab aa 
ab ff 
baba aa 
ab fff 

运行命令:

sed "s/^$var1/$var2/ ; ta ; b ; :a ; N ; ba" infile 

而且结果:

bb aa 
ab ff 
baba aa 
ab fff