Bash: How to Pad Numbers with Leading Zeros


Often you may want to use Bash to pad a number with leading zeros until it achieves a specific length.

You can use the following syntax to do so:

printf "%06g" 134

This particular example will pad the number 134 with enough leading zeros so that it achieves a total length of 6.

If we would like to store this result in a variable, we can use the -v flag followed by a variable name:

printf -v my_var "%06g" 134

This particular example will pad the number 134 with enough leading zeros so that it achieves a total length of 6 and then save the results to a variable named my_var.

Note that both of these methods use the printf command to format the number in a specific manner in Bash.

The following example shows how to use this syntax in practice.

Example: How to Pad Number with Leading Zeros in Bash

Suppose that we would like to pad the number 134 with enough leading zeros so that it has a total length of 6.

We can use the following syntax with printf to do so:

printf "%06g" 134

The following screenshot shows how to use this syntax in practice:

Bash pad number with leading zeros

Notice that this returns 000134, which represents the number 134 padded with enough zeros to have a total length of 6.

Note that we could also use the following syntax to pad the number 134 with leading zeros and save the results in a new variable named my_var:

printf -v my_var "%06g" 134

echo $my_var

The following screenshot shows how to use this syntax in practice:

Bash pad number with leading zeros and save to variable

Notice that when we use the echo statement to view the my_var variable, we can see that it contains a value of 000134.

Feel free to replace the 6 in “%06g” in the code with a different value to pad your own variable with a different number of leading zeros.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Remove Leading Zeros from a Variable
How to Remove newline from String in Bash
How to Remove Last Character from String in Bash

Leave a Reply