简体   繁体   中英

Using sed to search and replace an ip address in a file

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 :)

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.

sed -e 's/old ip/new ip/g' filename
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

这仅验证四个十进制八位字节表示,因此这个将失败 016.067.006.200(即使有效但不是四位十进制八位字节表示,而是八进制)

016.067.006.200 =~ 14.55.6.200

尝试这个:

sed -e 's/ \(\([0-9]\{1,3\}\.\)\{1,3\}\).[0-9]/NEW_IP/g'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM