Posts Tagged ‘padding’

leading zeros in bash scripts

July 18th, 2011 3 comments

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: , ,