我正在使用sed进行查找和替换,用BASH变量$a
替换BASH变量$b
(当在新行的开头时):
sed -i "s#^$a#$b#" ./file.txt
这取代了^$a
的所有匹配项。如何只替换整个文件中第一次出现的^a
?
答案 0 :(得分: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
答案 1 :(得分:4)
答案 2 :(得分:1)
这可能对您有用:
sed -i 'x;/^./{x;b};x;/^'"$a"'/{s//'"$b"'/;h}' file
或者:
sed -i ':a;$!{N;ba};s/^'"$a/$b"'/m' file