awk to substitute ip without zero left padding

Hello All,

I have this script to awk IP to new file.

#awk '/myip|yourip/ {sub(/...\....\....\..../, newip)}1' newip=$IP  existing.txt > new.txt

When existing.txt has myip=192.168.123.123 and $IP has 192.168.12.12, the awk script is not working. But while I add zero left padding to $IP i.e, 192.168.012.012 it works.

Same the case when myip=192.168.12.12 and $IP has 192.168.123.123, does not work.

Inshort, the IP format need to be 3 digit decimal to work. Any suggestions.

Regards
Shaan

I don't know whats the problem is.:rolleyes:

because it works perfect here..

$ cat file
myip=192.168.123.123

$ awk '/myip|yourip/{sub(/...\....\....\..../,newip)}1' newip="192.168.12.12" file
myip=192.168.12.12

could you please provide your sample input.

1 Like

Try /.+\..+\..+\..+/ instead of /...\....\....\..../ , or:

awk -F= '/myip|yourip/{sub($2, newip)}1' newip=$IP infile
1 Like

Thanks. /.+\..+\..+\..+/ instead of /...\....\....\..../ works, but that does not copy other text from existing.txt. it only captures IP.

But somehow, my existing code started working as Pamu noticed.