LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Replace IP address string in a file using sed (https://www.linuxquestions.org/questions/linux-newbie-8/replace-ip-address-string-in-a-file-using-sed-924504/)

finekevin 01-18-2012 05:48 PM

Replace IP address string in a file using sed
 
Hi Guys,

I am new to linux and I need your help!

I need to replace an IP address in a file using "sed" command. The IP address could be any number (random) and the double quotes(") must be present as part of the string. There are numerous IP addresses in the file, but I only need to replace IP address within the following string only.

Current IP address string:
MY_REM_IPADDR="X.X.X.X"

Note: X represents random number.

New IP address string would be:
MY_REM_IPADDR="10.5.34.23"


I am using Fedora Linux with bash shell. It is an embedded system, so I have limited packages and I can't install additional packages. This is the reason, I need to use "sed" command.

Thank you,
Kevin

Ser Olmy 01-18-2012 06:33 PM

To replace the IPv4 address in MY_REM_IPADDR="x.x.x.x" with something else, you could use this:

sed "s/\([0-9]\{1,3\}\.)\{3\}[0-9]\{1,3\}/new.ip.address/"

But that might replace other IP addresses as well. To match the exact string MY_REM_IPADDR="x.x.x.x" and replace the IPv4 address x.x.x.x with someting else, this should do the trick:

sed "s/^MY_REM_IPADDR=\"\([0-9]\{1,3\}\.)\{3\}[0-9]\{1,3\}/MY_REM_IPADDR=\"new.ip.address/"

The caret at the beginning matches the start of the line, so if MY_IP_ADDRESS could have preceding whitespace, it should be removed.

The regexp may seem unreadable, but that's mostly do to the excessive backslash escaping needed for bash. This it what's really going on:

[0-9] - Matches digits 0-9
[0-9]{1,3} - Matches from 1 to 3 digits (like in an IP address)
[0-9]{1,3}\. - Matches 1 to 3 digits followed by a dot (escape needed in regexes)
([0-9]{1,3}\.){3} - Exactly three sequences of 1 to 3 digits and a dot
([0-9]{1,3}\.){3}[0-9]{1,3} - ...followed another sequence, no dot this time

Now escape all parentheses and curly brackets, as well as the double quotes inside the regex, and it'll look like the above.

Andrew Benton 01-18-2012 07:16 PM

If you only want to replace the IP address on lines that contain the string MY_REM_IPADDR then limit the sed with that
Code:

sed '/MY_REM_IPADDR/s#[1-9.]*#10.5.34.23#'


All times are GMT -5. The time now is 09:20 AM.