Last Updated: September 27, 2021
· knowshan

Bash: Removing leading zeroes from a variable

There are at least two ways to do it:

Following example performs string replacement using sed.

# sed removes leading zeroes from stdin
new=$(echo $old | sed 's/^0*//')

bash built-in string manipulation
Following example uses bash buil-in string manipulation with extglob. The extglob is used to expand word '+(0)'. Please verify that your bash is using extglob by running 'shopt' command.

# Removes 1 or more longest occurrences from
# the beginning of the string

Check TLDP for more details on string manipulation.

3 Responses
Add your response

If I run the following at the bash promt:</p>
$ var="00087" $ newvar=${var##+(0)} $ echo $newvar </pre> </code> The results are as expected. The leading zeros are removed. However, once I put this in a script; it does not work. It does not remove the leading zeros. The shopt commands returns extglob on. I'm confused. </p> Now, look at this script:</p>


This works but if value of var=087 then it does not, that would yield 087

echo $newvar

This one works great as long as there are no zeros at the end

because a value like 320, 10, 50 200 would yields a blank.


echo $newvar // yields: a blank

This works as long as there are no zeros at the end. Well, that is not good either. Now what do I do? I guess I use sed.</p>

over 1 year ago ·

Or without extglob, we can use this.

over 1 year ago ·

Weirdly I noticed that if you add numbers with expr it sheds the leading 0's .
eg: expr 000100 + 0 #becomes 100

over 1 year ago ·