簡體   English   中英

替換文件中第一次出現的 sed 命令不起作用

[英]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

使用以下僅替換搜索字符串的第一個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始終為false
  • 1打印$0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM