Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

searching for ip addresses except 127.0.0.1 using regular expressions

Tags:

regex

linux

sed

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?

like image 650
Maksat Sapar Avatar asked Jan 09 '23 04:01

Maksat Sapar


1 Answers

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
like image 64
Avinash Raj Avatar answered Jan 25 '23 12:01

Avinash Raj