4

Using command line tools, I am trying to find any ip address except 127.0.0.1 and replace with a new ip. I tried using sed:

sed 's/\([0-9]\{1,3\}.[0-9]\{1,3\}.[0-9]\{1,3\}\)\(?!127.0.0.1\)/'$ip'/g' file

Please can you help me?

Telemachus
  • 19,459
  • 7
  • 57
  • 79

3 Answers3

5

Since sed won't support negative lookahead assertion, i suggest you to use Perl instead of sed.

perl -pe 's/\b(?:(?!127\.0\.0\.1)\d{1,3}(?:\.\d{1,3}){3})\b/'"$ip"'/g' file

Example:

$ cat file
122.54.23.121
127.0.0.1 125.54.23.125
$ ip="101.155.155.155"
$ perl -pe 's/\b(?:(?!127\.0\.0\.1)\d{1,3}(?:\.\d{1,3}){3})\b/'"$ip"'/g' file
101.155.155.155
127.0.0.1 101.155.155.155

Hacky one through the PCRE verb (*SKIP)(*F),

$ perl -pe 's/\b127\.0\.0\.1\b(*SKIP)(*F)|\b\d{1,3}(?:\.\d{1,3}){3}\b/'"$ip"'/g' file
101.155.155.155
127.0.0.1 101.155.155.155
Community
  • 1
  • 1
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
2

Assuming you have something like this in your file my_file

127.0.0.1 192.152.30.1
158.30.254.1 127.0.0.1
158.40.253.10 127.0.0.1

You can try the command line below

sed -r 's/127.0.0.1/########/g;s/[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}/MY_NEW_IP/g;s/########/127.0.0.1/g' my-file

I am assuming you have nothing like ######## in your file

take all 127.0.0.1 replace it with ######## then target all ip address where you will substitute your new ip. Afterwards replace ######## with 127.0.0.1

results

127.0.0.1 MY_NEW_IP
MY_NEW_IP 127.0.0.1
MY_NEW_IP 127.0.0.1

if you are substituting a variable ensure you double quote

 sed -r "................................." my_file
repzero
  • 8,254
  • 2
  • 18
  • 40
2

Using standard unix tools here is an awk version:

awk -v ip='aa.bb.cc.dd' '{for (i=1; i<=NF; i++) 
       if ($i != "127.0.0.1" && $i ~ /\<[0-9]{1,3}(\.[0-9]{1,3}){3}\>/) $i=ip} 1' file
127.0.0.1 aa.bb.cc.dd
aa.bb.cc.dd 127.0.0.1
aa.bb.cc.dd 127.0.0.1

cat file
127.0.0.1 192.152.30.1
158.30.254.1 127.0.0.1
158.40.253.10 127.0.0.1
anubhava
  • 761,203
  • 64
  • 569
  • 643