0

I referred posts:

Sed command : how to replace if exists else just insert?

https://superuser.com/questions/590630/sed-how-to-replace-line-if-found-or-append-to-end-of-file-if-not-found

But none of the solution seems to be working. Can anybody explain why?

I am just executing the commands on the terminal by making that particular file

sed -e 's/^avpgw/new text/' -e t -e 's/^av/new text/' -e t -e 's/^/new text/' file

sed '/^FOOBAR=/{h;s/=.*/=newvalue/};${x;/^$/{s//FOOBAR=newvalue/;H};x}' infile
Community
  • 1
  • 1
hgoel
  • 3
  • 4

2 Answers2

3

Test case:

$ cat > file
match
miss

Solution in awk:

$ awk 'sub(/match|$/,"hit")' file
hit
misshit

ie. replace the first match or the end-of-record $, whichever comes first.

James Brown
  • 36,089
  • 7
  • 43
  • 59
0

With sed:

sed '/match/{s/match/replace/g;p;D}; /match/!{s/$/replace/g;p;D}' file

Test:

$ cat file
some text... match ... some text
some text only here...
..... here also...

$ sed '/match/{s/match/replace/g;p;D}; /match/!{s/$/replace/g;p;D}' file
some text... replace ... some text
some text only here...replace
..... here also...replace

Note: Use -i for edit files in place.

sat
  • 14,589
  • 7
  • 46
  • 65