Site icon Bytefreaks.net

Linux Bash: How to print leading zeroes on a variable

Advertisements

In order to print the leading zeros to a variable you need to use the function printf as follows, where %03d states that the number should consist of minimum 3 digits and thus it will put the missing leading zeros:

 printf %03d $counter

The following example renames a file that it has the following format for a filename: number.anything and adds the leading zeros in order to make it easier while sorting multiple files.
The name is contained in the variable $a.
If for example we had the file 11.txt  it will become 0011.txt

mv $a `printf %04d.%s ${a%.*} ${a##*.}`

 

This post is also available in: Greek

Exit mobile version