How to Remove Leading Zeros from a Variable in Bash


Often you may want to use Bash to remove leading zeros from a variable.

There are two common ways to do so:

Method 1: Remove Leading Zeros Using sed

no_zero=$(echo $my_number | sed 's/^0*//')

This particular example will remove all leading zeros from the variable named my_number and store the results in a new variable named no_zero.

This method uses the sed command s/ to perform a “substitution”, by substituting all leading zeros with nothing, which has the same effect as removing all leading zeros from the variable.

Method 2: Remove Leading Zeros Using expr

no_zero=$(expr $my_number + 0)

This particular example will also remove all leading zeros from the variable named my_number and store the results in a new variable named no_zero.

This method uses the expr command to evaluate the result of adding zero to the variable named my_number, which returns the result with all leading zeros automatically removed.

The following examples show how to use each of these methods in practice.

Example 1: Remove Leading Zeros Using sed

Suppose we create a variable in Bash named my_number that contains the following value:

  • 00004588

Suppose that we would like to remove all leading zeros from this variable.

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

my_number=00004588
no_zero=$(echo $my_number | sed 's/^0*//')

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

Bash remove leading zeros from variable

Notice that this returns the value from the my_number variable with all leading zeros removed.

Example 2: Remove Leading Zeros Using expr

Once again, suppose we create a variable in Bash named my_number that contains the following value:

  • 00004588

Suppose that we would like to remove all leading zeros from this variable.

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

my_number=00004588
no_zero=$(expr $my_number + 0)

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

Bash remove leading zeros using expr

This returns the value from the my_number variable with all leading zeros removed.

Related Tutorials

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

How to Remove Spaces from String in Bash
How to Remove newline from String in Bash
How to Remove Last Character from String in Bash

Leave a Reply