用sed替换匹配的第一次出现

时间:2012-02-05 02:42:40

标签: bash sed

我正在使用sed进行查找和替换,用BASH变量$a替换BASH变量$b(当在新行的开头时):

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

这取代了^$a的所有匹配项。如何只替换整个文件中第一次出现的^a

3 个答案:

答案 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)

这应该有效:

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

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

了解详情

答案 2 :(得分:1)

这可能对您有用:

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

或者:

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