Home > bashism > leading zeros in bash scripts

leading zeros in bash scripts

I have a bash script that generates names for binaries, these names include parameters ranging from 2 to 64. I sort these then but due to the nature of alphanumeric sorting, 4 is sorted between 32 and 64 (4 is bigger than 3 but smaller than 6…). So what i need is leading zeros for the sorting to work the way i want it to work. The easiest solution i could come up with is padding zeros c-style using the command line version of printf:

PARAMLIST="2 4 8 16 24 32 40 48 56 64"
  printf "%02d\n" $PARAM

[update by bert]

sort –numeric-sort

solves the sorting issue as well :)

Categories: bashism Tags: , ,
  1. bert
    July 18th, 2011 at 19:54 | #1

    When you have to sort something numerical the next time, but don’t have control over the input, than try `sort –numeric-sort`.

  2. stefan
    July 21st, 2011 at 13:28 | #2

    For creating numbers with leading zeros in a script one can use

    PARAMLIST=`/usr/bin/seq -f %02.0f 1 2 64`
    PARAMLIST=`/usr/bin/seq -w 1 2 64`

    …not what posts task is, but maybe helps some other time ;)

  1. No trackbacks yet.