我正在用sed进行查找和替换,用BASH变量替换BASH变量$a(当在新行的开头时)$b:
sed -i "s#^$a#$b#" ./file.txt
Run Code Online (Sandbox Code Playgroud)
这取代了所有匹配^$a.如何只替换^a整个文件中的第一个匹配项?
一种方式使用sed:
sed "s/^$var1/$var2/ ; ta ; b ; :a ; N ; ba" infile
Run Code Online (Sandbox Code Playgroud)
说明:
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.
Run Code Online (Sandbox Code Playgroud)
由Jaypal提供的相同示例的测试:
内容infile:
ab aa
ab ff
baba aa
ab fff
Run Code Online (Sandbox Code Playgroud)
运行命令:
sed "s/^$var1/$var2/ ; ta ; b ; :a ; N ; ba" infile
Run Code Online (Sandbox Code Playgroud)
结果:
bb aa
ab ff
baba aa
ab fff
Run Code Online (Sandbox Code Playgroud)