railsuser400
railsuser400

Reputation: 1023

Using sed to replace IP using regex

Assuming a simple text file:

123.123.123.123

I would like to replace the IP inside of it with 222.222.222.222. I have tried the below but nothing changes, however the same regex seems to work in this Regexr

sed -i '' 's/(\d{1,3}\.){3}\d{1,3}/222.222.222.222/' file.txt

Am I missing something?

Upvotes: 1

Views: 224

Answers (2)

fedorqui
fedorqui

Reputation: 289565

You'd better use -r, as indicated by anubhava.

But in case you don't have it, you have to escape every single (, ), { and }. And also, use [0-9] instead of \d:

$ sed 's/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/222.222.222.222/' <<< "123.123.123.123"
222.222.222.222

Upvotes: 1

anubhava
anubhava

Reputation: 785058

Two problems here:

  • sed doesn't like PCRE digit property \d, use range: [0-9] or POSIX [[:digit:]]
  • You need to use -r flag for extended regex as well.

This should work:

s='123.123.123.123'
sed -r 's/([0-9]{1,3}\.){3}[0-9]{1,3}/222.222.222.222/' <<< "$s"
222.222.222.222

Better would be to use anchors to avoid matching unexpected input:

sed -r 's/^([0-9]{1,3}\.){3}[0-9]{1,3}$/222.222.222.222/' <<< "$s"

PS: On OSX use -E instead of -r:

sed -E 's/^([0-9]{1,3}\.){3}[0-9]{1,3}$/222.222.222.222/' <<< "$s"
222.222.222.222

Upvotes: 1

Related Questions