IP with padded zeroes in bash
To create a weblink I needed to pad zeroes to an IP
Because I couldn't find any examples I created my own. I invite anyone to improve on it and hopefully I'll see many alternatives. I'm using 'grep -o' to break down the 4 segments.... Code:
# IP=127.0.0.1 |
A first improvement would be the choice of a single tool to perform the task. For example in awk:
Code:
echo $IP | awk -F. '{ OFS = FS; for ( i = 1; i <= NF; i++ ) $i = sprintf("%03d",$i); print }' |
Using bash
Code:
printf '%03d.%03d.%03d.%03d' ${IP//./ } |
IP address "octets" are in decimal. Left-side padding with 0s can result in them being interpreted as octal numbers. That doesn't matter for the likes of 000 and 001 but 071 for example would be 57 in decimal.
|
I found one or more problems with the examples given above (could be typos, could be system differences, who knows..)
EDIT: Must have been a death-defying series of typos on my part :scratch: as the other methods now work for me. While this method may be no better, it appears to work for me: Code:
echo $ip | awk -v RS="." '{if(out != ""){out = out"."}; out = out sprintf("%03u",$0)} END{print out}' Code:
echo $ip | sed "s/\([0-9]*\).\([0-9]*\).\([0-9]*\).\([0-9]*\)/ printf "%03u.%03u.%03u.%03u" \1 \2 \3 \4 /ge" |
Due to catkin's post I've noticed a weakness in the printf method I posted.
It can give wrong results if there are any existing leading zeros in the IP, e.g. Code:
IP=020.030.073.0 |
I like this one:
Quote:
Quote:
|
Quote:
Keep them coming!! |
All times are GMT -5. The time now is 06:18 PM. |