hgoel
hgoel

Reputation: 3

How to replace line if found or append to end of file if not found in shell script?

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

Upvotes: 0

Views: 1836

Answers (2)

sat
sat

Reputation: 14949

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.

Upvotes: 0

James Brown
James Brown

Reputation: 37424

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.

Upvotes: 3

Related Questions