Search for ip addresses except 127.0.0.1 using regular expressions

Using command line tools, I try to find any IP address except 127.0.0.1, and replace it 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 help me?

+4
source share
3 answers

Since sed will not support the negative lookahead statement, I suggest you 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

Hacker using the verb PCRE (*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
+5
source

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 assume you have nothing like this ########in your file

127.0.0.1 ########, IP-, ip. ######## 127.0.0.1

127.0.0.1 MY_NEW_IP
MY_NEW_IP 127.0.0.1
MY_NEW_IP 127.0.0.1

, ,

 sed -r "................................." my_file
+2

Using standard unix tools is the awkversion:

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
+2
source

Source: https://habr.com/ru/post/1569123/


All Articles