Sed command : how to replace if exists else just insert?
linux, sed
Solution
You can do it this way:
sed -e 's/^avpgw/new text/' -e t -e 's/^av/new text/' -e t -e 's/^/new text/' file
This replaces the pattern with `new text` (s///) and jumps to the end (t). Otherwise it tries the next pattern. See also sed commands summary.
You can also separate the commands with `;`:
sed 's/^avpgw/new text/; t; s/^av/new text/; t; s/^/new text/' file
or put the commands in a sed command file:
s/^avpgw/new text/
t
s/^av/new text/
t
s/^/new text/
and call it this way:
sed -f commandfile file
If you want to ignore case, append an i at the end of the substitute command as in `s/^av/new text/i`. Another way is to spell it out with character sets `s/^[aA][vV]/new text/`. But that is not `sed` specific, for this you can search for regular expressions in general.
Since the replacement text is always the same, another approach could be to remove `avpgw` and `av`, and then insert `new text` at the beginning
sed -e 's/^avpgw//' -e 's/^av//' -e 's/^/new text/' file.txt
Be aware, that this would also remove a leading `avpgwav`. So this might or might not be, what you want.
Problem
I need to edit several lines in a file such that if a line begins with (av or avpgw) then replace these with new text, else just insert the new text in beginning. How can I do this using sed ?