Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 387
twistedpixel Avatar asked Mar 11 '11 18:03

twistedpixel


People also ask

How do I use sed to edit a file?

The procedure to change the text in files under Linux/Unix using sed: Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace.

How do you replace a variable in a file using sed?

For replacing a variable value using sed, we first need to understand how sed works and how we can replace a simple string in any file using sed. In this syntax, you just need to provide the string you want to replace at the old string and then the new string in the inverted commas.

Which sed command is used for replacement?

Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line. Output : linux is great os.


1 Answers

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.

like image 62
heijp06 Avatar answered Oct 11 '22 15:10

heijp06