Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripping leading zeros using bash substring removal only

Tags:

bash

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?

like image 973
user2969118 Avatar asked Nov 08 '13 14:11

user2969118


3 Answers

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
like image 75
devnull Avatar answered Nov 16 '22 07:11

devnull


Working with minutes and hours in a cron job generator script I found that leading zeros in front of 08 & 09 cause bash to think the value is an invalid octal amount. The script could not just strip leading zeros because a single zero is still valid. The solution was to pipe to bc.

HOUR=09
echo $HOUR | bc
9

HOUR=0
echo $HOUR | bc
0

HOUR=14
echo $HOUR | bc
14
like image 42
LinuxGuru Avatar answered Nov 16 '22 06:11

LinuxGuru


Yet another way, although this requires the extglob functionality being enabled:

echo ${string/#+(0)/}
like image 8
twalberg Avatar answered Nov 16 '22 05:11

twalberg