bash

Stripping leading zeros using bash substring removal only


I am aware of other ways to solve this problem that do work (and I am currently using the 'expr' method), but it bugs me that I cannot figure out how to do it with the bash built-in functions only.

When I try to strip the leading zeros from a variable using the ${variable##remove} construct I can either only get it to remove one zero or all numbers.

string="00123456"
echo "${string##0}" // Only the first 0 is removed
echo "${string##0*0}" // The whole string is removed
echo "${string#0*0}" // Works

string="01230"
echo "${string##0}" // Works
echo "${string##0*0}" // The whole string is removed
echo "${string#0*0}" // Again, the whole string is removed

I read the bash manual twice to see if I am doing it correctly, but the official documentation is sparse at best. I am aware that enabling extglob may also solve this problem but it seems like overkill for a problem as simple as this.

Am I missing something obvious or is it really that hard to remove one or more leading zeros from a string using bash functions only?


Solution

  • The following would remove all the leading 0s from the string:

    $ string="000123456000"
    $ echo "${string#"${string%%[!0]*}"}"
    123456000
    

    Saying "${string%%[!0]*}" would return the match after deleting the longest trailing portion of the string that satisifies [!0]* -- essentially returning the zeros at the beginning.

    "${string#"${string%%[!0]*}"}" would remove the part returned by the above from the beginning of the string.


    Alternatively, you could use shell arithmetic:

    $ string="0000123456000"
    $ echo $((10#$string))
    123456000