[英]sed command to replace first occurrence in file is not working
我正在嘗試替換文件中出現的第一個字符串。 例如,嘗試用linux替換第一個foo
樣本.txt
Hi foo bar
This is again foo bar.
命令: sed '0,/foo/s//linux/' sample.txt
上面命令的實際 output (基本上沒有變化)
Hi foo bar
This is again foo bar.
我預期的 output 如下
Hi linux bar
This is again foo bar.
有人可以幫忙嗎?
/tmp/test.txt
Hi foo bar!
This is again foo bar
使用以下sed 命令僅替換搜索字符串的第一個orrouance;
sed -e '1 s/foo/linux/; t' -e '1,// s//linux/' /tmp/test.txt
結果:
Hi linux bar!
This is again foo bar
對於任何awk
以下可能會有所幫助:
awk '/foo/ && ++count==1{sub(/foo/,"linux")} 1' Input_file
使用 GNU sed
如果有足夠的 memory 在下面的框中可能會有所幫助:
sed -z 's/foo/linux/' Input_file
帶awk
awk '!f && sub(/foo/, "linux"){f=1} 1' ip.txt
!f
將為真,因為未初始化的變量默認為假sub(/foo/, "linux")
將替換第一次出現的foo
並返回1
- 從而使f=1
和后續的!f
始終為false1
打印$0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.