LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   sed: global search and replace if a string isn't anywhere in that line (http://www.linuxquestions.org/questions/linux-general-1/sed-global-search-and-replace-if-a-string-isn%27t-anywhere-in-that-line-933614/)

linux_kung_fu 03-09-2012 10:12 AM

sed: global search and replace if a string isn't anywhere in that line
 
Having an issue with finding how to do a global search/replace if a string isn't found on that line.

I've got thousands of files where I need to search/replace one IP for another, but only if a specific string isn't also on that line.

Any ideas?

druuna 03-09-2012 10:21 AM

Hi,

Do you need a sed solution or will awk do?

An awk solution:
Code:

awk '!/string/ { sub(/10.0.0.1/,"254.254.254.254")} { print }' infile
Example run:
Code:

$ cat infile
10.0.0.1 string
172.16.0.1
192.168.0.1
10.0.0.1

$ awk '!/string/ { sub(/10.0.0.1/,"254.254.254.254")} { print }' infile
10.0.0.1 string
172.16.0.1
192.168.0.1
254.254.254.254

Hope this helps.

linux_kung_fu 03-09-2012 10:37 AM

awk would be fine, however that appears to write that to stdout. How would I get it to commit the changes to 'infile'? Thanks!

druuna 03-09-2012 10:43 AM

Hi,
Quote:

Originally Posted by linux_kung_fu (Post 4622815)
awk would be fine, however that appears to write that to stdout. How would I get it to commit the changes to 'infile'? Thanks!

Awk doesn't have a -i option like sed does, you need an extra command:
Code:

awk '!/string/ { sub(/10.0.0.1/,"254.254.254.254")} { print }' infile > outfile
mv outfile infile

The awk command puts its output in outfile, the mv command moves it to infile (the original will be lost!!).

Can also be written on one line:
Code:

awk '!/string/ { sub(/10.0.0.1/,"254.254.254.254")} { print }' infile > outfile ; mv outfile infile
Hope this helps.

linux_kung_fu 03-09-2012 10:49 AM

Thank you, didn't see an '-i' equivalent. Probably best that I write it to another file first and make sure I'm doing what I want done properly then mv things over. Thanks.

colucix 03-09-2012 10:53 AM

Actually GNU awk can edit the file in place (I think it uses the same approach explained by druuna but hidden from the user). Example:
Code:

awk '!/string/ { sub(/10.0.0.1/,"254.254.254.254")} { print > FILENAME }' infile
See the add-on in blue, where FILENAME is an internal awk variable. Again the original file is lost.


All times are GMT -5. The time now is 05:01 AM.