0

I'm trying to search and replace a string in a file on the Mac Terminal using sed. I'm able to search and replace a simple string:

sed -i.bak 's/HOSTS/BOASTS/g' file.txt

But I'm trying it on something a little more complicated, basically the string I want to replace looks something like 'HOSTS:"123.123.123.123, 12345"' - with the 123.123.123.123 being a variable IP so I can't exactly search for that, so I'm trying to use regular expressions, mainly the "." to indicate that I don't know what the IP address will be.

I've tried the following with no luck:

sed -i.bak 's/HOSTS:"., 00000"/HOSTS:"999.999.999.999, 00000"/g' file.txt

1 Answer 1

1

You could try the following:

echo "HOSTS:\"123.123.123.123, 12345\"" | sed -e 's/[0-9][0-9][0-9]\.[0-9][0-9][0-9]\.[0-9][0-9][0-9]\.[0-9][0-9][0-9]/999.999.999.999/g'.

each [0-9] will look for a digit, and each \. is the actual symbol, not the "match a character" symbol on sed. This assumes that the IPs will always have this structure. If you're dealing with xxx.xxx.xxx.xxx:xxxx you'll have to edit accordingly.

Sign up to request clarification or add additional context in comments.

1 Comment

I suggest a more permissive IP regex: [0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+/ where '\+' signals 1 or more of the preceding character This will work for IP addresses such as 4.2.2.2 (a valid IP).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.