Monday, July 13, 2015

Remove Leading Zeros from IP Address

I was working on some automation where I'd need to translate an IP address that was always represented as 3 digits per octet - like 001.002.003.004 instead of 1.2.3.4.

Since I didn't want to reinvent the wheel I went to Google and to my surprise found no examples that worked well - some would only remove 1 leading zero.

So, after some testing and code borrowing, here are two solutions:

Using sed:
sed -r 's/^0*([0-9]+)\.0*([0-9]+)\.0*([0-9]+)\.0*([0-9]+)$/\1.\2.\3.\4/'

Using awk:
awk -F'[.]' '{w=$1+0; x=$2+0; y=$3+0; z=$4+0; print w"."x"."y"."z}'

POC:
$ echo 001.002.003.004 | sed -r 's/^0*([0-9]+)\.0*([0-9]+)\.0*([0-9]+)\.0*([0-9]+)$/\1.\2.\3.\4/'
1.2.3.4
$ echo 001.002.003.004 | awk -F'[.]' '{w=$1+0; x=$2+0; y=$3+0; z=$4+0; print w"."x"."y"."z}'
1.2.3.4