Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
948 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/([0-9]{1,3}.){3}[0-9]{1,3}'/"$newip"/

BTW this solution still matches strings that do not represent IP addresses. See this site under IP Adresses for more complex solutions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...