Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 784
user1765709 Avatar asked Oct 22 '12 14:10

user1765709


People also ask

How do you replace something with 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.

How do you use sed to replace the first occurrence in a file?

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.

Does sed support multiline replacement?

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.


2 Answers

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.

like image 100
Olaf Dietsche Avatar answered Oct 11 '22 03:10

Olaf Dietsche


This might work for you (GNU sed):

sed -r 's/^av(pgw)?.*/replacement/;t;s/^/replacement /' file
like image 29
potong Avatar answered Oct 11 '22 03:10

potong