我做一个查找和使用sed替换,与BASH变量$b
更换BASH变量$a
(在新行的开始时):更换比赛的第一次出现使用sed
sed -i "s#^$a#$b#" ./file.txt
这将替换^$a
的所有匹配项。我怎样才能在整个文件中只替换^a
的第一次出现?
我做一个查找和使用sed替换,与BASH变量$b
更换BASH变量$a
(在新行的开始时):更换比赛的第一次出现使用sed
sed -i "s#^$a#$b#" ./file.txt
这将替换^$a
的所有匹配项。我怎样才能在整个文件中只替换^a
的第一次出现?
此阅读更多有关这可能为你工作:
sed -i 'x;/^./{x;b};x;/^'"$a"'/{s//'"$b"'/;h}' file
或者:
sed -i ':a;$!{N;ba};s/^'"$a/$b"'/m' file
一你的方式唱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
我使用GNU sed的版本4.2.1。 – Village 2012-02-05 03:15:45