3

I am formatting numbers in a bash script with printf

printf "%04d" $input   # four digits width with leading zeros if shorter

If input="011" printf assumes the value is octal and returns 0009 instead of 0011.

Is it possible to force printf to assume all values are decimal?

lojoe
  • 521
  • 1
  • 3
  • 13
  • 3
    Why not just remove the leading zeroes when you assign to `input`? – Barmar Jan 06 '17 at 19:06
  • In that case I have to check any input if it starts with a zero. I think the answer from chepner/jackman is more concise. – lojoe Jan 06 '17 at 19:23
  • You have to check your input anyway, right? you're not just using user input without checking anything, right? so why not use a regex like `if [[ $input =~ ^0*([[:digit:]]*)$ ]]; then input=${BASH_REMATCH[1]}; printf '%04d\n' "$input"; else echo 'bad input'; fi`. – gniourf_gniourf Jan 07 '17 at 11:04
  • @Barmar gave me the idea for `while echo "$input"|grep -q '^0';do input=$(echo "$input"|cut -c2-);done` – Alexx Roche Dec 30 '18 at 12:54

1 Answers1

6

Prefix the value with a base specifier of 10#.

$ printf "%04d\n" "$input"
0009
$ printf "%04d\n" "$((10#$input))"
0011
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
chepner
  • 497,756
  • 71
  • 530
  • 681