Bash: Removing leading zeroes from a variable
There are at least two ways to do it:
sed
Following example performs string replacement using sed.
old="0004937"
# 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.
old="0004937"
# Removes 1 or more longest occurrences from
# the beginning of the string
new=${old##+(0)}
Check TLDP for more details on string manipulation.
Written by Shantanu
Related protips
3 Responses
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>
var="00087"
This works but if value of var=087 then it does not, that would yield 087
newvar=${var##0*0}
echo $newvar
<br>
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.
var="8700"
newvar=${var##*0}
echo $newvar // yields: a blank
</code>
</pre>
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>
Or without extglob, we can use this.
old="0004937"
new=$((10#$old))
Weirdly I noticed that if you add numbers with expr it sheds the leading 0's .
eg: expr 000100 + 0 #becomes 100