简体   繁体   中英

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?

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

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

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