bash 用 sed 替换第一次匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9146504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing first occurance of a match with sed
提问by Village
I am doing a find and replace with sed, replacing the BASH variable $a(when at the start of a new line) with the BASH variable $b:
我正在做一个查找并用 sed 替换,用 BASH 变量替换 BASH 变量$a(在新行的开头)$b:
sed -i "s#^$a#$b#" ./file.txt
This replaces all matches for ^$a. How can I replace only the first occurrence of ^awithin the entire file?
这将替换 的所有匹配项^$a。如何仅替换^a整个文件中的第一次出现?
回答by Birei
One way using sed:
一种使用方式sed:
sed "s/^$var1/$var2/ ; ta ; b ; :a ; N ; ba" infile
Explanation:
解释:
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.
A test with same example provided by Jaypal:
Jaypal 提供的具有相同示例的测试:
Content of infile:
内容infile:
ab aa
ab ff
baba aa
ab fff
Run the command:
运行命令:
sed "s/^$var1/$var2/ ; ta ; b ; :a ; N ; ba" infile
And result:
结果:
bb aa
ab ff
baba aa
ab fff
回答by Bruno Silva
This should work:
这应该有效:
sed -i "0,/^$a/s//$b/" ./file.txt
You can read more about this at http://www.grymtheitroade.com/Unix/Sed.html#toc-uh-29
您可以在http://www.grymtheitroade.com/Unix/Sed.html#toc-uh-29阅读更多相关信息
回答by potong
This might work for you:
这可能对你有用:
sed -i 'x;/^./{x;b};x;/^'"$a"'/{s//'"$b"'/;h}' file
Or:
或者:
sed -i ':a;$!{N;ba};s/^'"$a/$b"'/m' file

