IP address string manipulation problem

I am trying to build three octets 10.AB.C9 from a 5 digit number: 12ABC:

  • 12 = first octet
  • AB = Second octet
  • C = Third octet

There are two scenarios with my existing code that can cause an in correct IP to generate.
If C has a leading zero for example: 02 then the third octet will 027 and IPs can’t have hardcoded leading zeros.


if [ "${five_digits:4:1}" -eq 0 ]; then

elif [ "${five_digits:4:1}" -ne 0 ]; then

The above code solves the leading zero problem in C

The second scenario is where A is zero meaning the second octet will have a leading zero. I am not sure how to handle that scenario and hopefully make the script simpler.

Asked By: Cruise5


I would break each octet apart, and remove any leading zeroes from each, then concatenate them together. Something like this:

if [[ ${#str} != 5 ]] || [[ ${str:0:2} != "12" ]]; then
    echo invalid input >&2;
    exit 1;
a=10               # first octet, constant
b=${str:2:2}       # second octet
b=${b#0}           # remove one leading zero
c=${str:4:1}9      # third octet
c=${c#0}           # remove one leading zero

res="$a.$b.$c"     # concatenated result
echo "$res"

E.g. that turns the input string 12345 to 10.34.59; 12055 to 10.5.59; and 12000 to 10.0.9.

Answered By: ilkkachu
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.