I am trying to replace first string occurrence in file. eg 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?
/tmp/test.txt
Hi foo bar!
This is again foo bar
Use the following sed 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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.