sed command to replace first occurrence in file is not working

Viewed 1855

I am trying to replace first string occurrence in file. e.g. Trying to replace first foo with linux

sample.txt

Hi foo bar
This is again foo bar.

Command: sed '0,/foo/s//linux/' sample.txt

Actual output from above command (basically no change)

Hi foo bar
This is again foo bar.

My expected output is as below

Hi linux bar
This is again foo bar.

Could anyone please help here?

3 Answers

With any awk following may help:

awk '/foo/ && ++count==1{sub(/foo/,"linux")} 1' Input_file

With GNU sed if one has enough memory in box following may help:

sed -z 's/foo/linux/' Input_file

With awk

awk '!f && sub(/foo/, "linux"){f=1} 1' ip.txt
  • !f will be true as uninitialized variables are falsey by default
  • sub(/foo/, "linux") will replace first occurrence of foo and returns 1 - thus making f=1 and subsequent !f to be always false
  • 1 to print $0
Related