Is there an easy way to get the POSIX shell to interpret numbers with leading zeroes as decimal?

StackOverflow https://stackoverflow.com/questions/21912089

  •  14-10-2022
  •  | 
  •  

Question

In a POSIX shell script, I'd like to use decimal numbers generated by seq -w both in string manipulations and in simple calculations using $(( ... )). This breaks because numbers with leading zeroes are interpreted as octal numbers. I have come up with something like this to actually get decimal numbers...

for n in $(seq -w 0 300); do
    str="xxx $n"
    dec=$(echo $n | sed -e 's,00*\(..*\)$,\1,')
    ...
done

... but I wonder if there's an easier / more obvious way to do this.

Was it helpful?

Solution

Use expr instead. eg instead of

for n in $(seq -w 0 10); do echo $n $((n + 4)); done

Use this:

for n in $(seq -w 0 10); do echo $n $(expr $n + 4); done

OTHER TIPS

Rather than generate 0-padded strings with seq, generate decimal numbers and pad them with zeros with printf when necessary.

for n in $(seq 0 300); do
    padded_n=$(printf '%03' "$n")
    ...
done

Hopefully, you know the upper-bound ahead of time. If not, you can use something uglier like

upper_bound=300
for n in $(seq 0 $upper_bound); do
    padded_n=$(printf "%0${#upper_bound}d" "$n")
    ...
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top