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 ?
Find and replace text within a file using sed command The procedure to change the text in files under Linux/Unix using sed: Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace.
With GNU sed's -z option you could process the whole file as if it was only one line. That way a s/…/…/ would only replace the first match in the whole file. Remember: s/…/…/ only replaces the first match in each line, but with the -z option sed treats the whole file as a single line.
By using N and D commands, sed can apply regular expressions on multiple lines (that is, multiple lines are stored in the pattern space, and the regular expression works on it): $ cat two-cities-dup2.
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.
This might work for you (GNU sed):
sed -r 's/^av(pgw)?.*/replacement/;t;s/^/replacement /' file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With