BASH - Remote leading zero in IP Address

Viewed 202

I've got the following bash command, which does remove a leading zero.. but it also removes a single zero which is wrong.

echo $ip | sed 's/\.0\{1,2\}/\./g' | sed 's/^0\{1,2\}//'

if $ip is 192.168.1.01  the result should be 192.168.1.1
if $ip is 192.168.01.01  the result should be 192.168.1.1
if $ip is 192.168.0.01  the result should be 192.168.0.1
if $ip is 192.168.0.0  the result should be 192.168.0.0
etc

What I'm getting is 192.168.0.0 becomes 192.168.. or 192.168.0.01 becomes 192.168..1

Any idea how to do this ?

Thanks

1 Answers

What you are doing now is replacing any .0 with .. This will obviously catch 1.1.0.0 as well.

This will work:

echo $ip | sed 's/\.0\+\([1-9]\)/\.\1/g; s/^0\+//'

Here we are looking for .0[1-9] which will only match a leading 0 that is followed by another number. You see I used \([1-9]\) which saves the trailing number and is placed into the substitution with \1.

EDIT:

@tomgalpin made a good point about leading 0s in the beginning. I don't have a smooth way of handling this with one command, so I just appended that as a separate substitution: s/^0\+//.

EDIT 2

Looks like my solution does not work with --posix option because of the +. Replacing this with * will work as well though it is making redundant matches. Also with -E, it is a little cleaner:

echo $ip | sed -E 's/\.0*([1-9])/\.\1/g; s/^0*//'
Related