Using sed to search and replace an ip address in a file
Solution 1
If your version of sed
supports extended regular expressions (the -r
option), you could do something like this (which is similar to what you have in your grep
statement). Also note $newip
is outside the single quotes to allow the shell to replace it.
sed -r 's/(\b[0-9]{1,3}\.){3}[0-9]{1,3}\b'/"$newip"/
BTW this solution still matches strings that do not represent IP addresses. See this site under IP Adresses for more complex solutions.
Solution 2
sed -e 's/old ip/new ip/g' filename
Solution 3
IP=207.0.0.2; [[ x${IP}x =~ x"(2([0-4][0-9])|2(5[0-5])|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(2([0-4][0-9])|2(5[0-5])|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(2([0-4][0-9])|2(5[0-5])|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(2([0-4][0-9])|2(5[0-5])|1[0-9][0-9]|[1-9][0-9]|[0-9])"x ]] && echo ok || echo bad
this validates only four decimal octet representation so this one will fail 016.067.006.200 (even valid but not four decimal octet representation, but octal)
016.067.006.200 =~ 14.55.6.200
Related videos on Youtube
twistedpixel
Updated on May 25, 2020Comments
-
twistedpixel almost 4 years
Been trying to get this working for a while and not really quite getting it. Basically, I have a file with an ip address that changes more or less on a daily basis. The file only contains one ip address and this is the one I'm trying to replace with my crazy grepping to find my current internal ip.
I have this
#!/bin/sh newip=$(ifconfig | grep 0xfff | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | grep -v 255) echo $newip sed 's/*\.*\.*\.*/"$newip"/g' log.txt > logmod.txt
but it's not matching and replacing. I'm not familiar with sed and I am a beginner with regexps too.
Any help would be awesome! Thanks :)
-
Steve Emmerson about 13 yearsBe advised that the "\b" (word boundary) construct isn't standard.
-
heijp06 about 13 years@Steve: That's true. I tested the expression with GNU sed version 4.2.1. Since the OP added the
bash
tag I assumed he might have some version of GNU sed as well. Also note that I specifically mention the-r
option. -
twistedpixel about 13 yearsYou, my friend, have saved me so many hours of stress! My version of sed did not unfortunately support -r so I used homebrew (I'm using a Mac) and installed the latest version which worked perfectly!
-
tripleee over 4 yearsSurely the OP wants the replacement to be the value of a variable, not the static text
NEW_IP
. The single quotes inhibit variable interpolation, and anyway, the existing answers already cover this. -
Martin Gal almost 4 yearsPlease don't simply post code. Add some context to your answer. Take a look at How to answer