2

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?

anubhava
  • 761,203
  • 64
  • 569
  • 643
Ajay Kedare
  • 120
  • 1
  • 7
  • You are missing the `-i` flag, which replace the contents of the file – Paolo Aug 20 '20 at 12:39
  • What is not working? replacement? or in-place edit? – Inian Aug 20 '20 at 12:41
  • 1
    It doesn't matter for now, whether to replace inline in the file or display it. My first focus is to get it to work. – Ajay Kedare Aug 20 '20 at 12:43
  • 2
    if you look at https://stackoverflow.com/q/148451/5291015, you fill find that your attempt only works on GNU sed and not on the one provided native with MacOS – Inian Aug 20 '20 at 12:55

3 Answers3

5

/tmp/test.txt

Hi foo bar!
This is again foo bar

Use the following commando to replace only the first orrouance of the search-string;

sed -e '1 s/foo/linux/; t' -e '1,// s//linux/' /tmp/test.txt

Result:

Hi linux bar!
This is again foo bar

0stone0
  • 34,288
  • 4
  • 39
  • 64
3

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
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
2

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
Sundeep
  • 23,246
  • 2
  • 28
  • 103