Removing initial zero from variables
Johnny Rosenberg
gurus.knugum at gmail.com
Sat Feb 18 18:54:34 UTC 2012
Here's yet another bash question, I know I asked quite a few lately:
I have a little problem regarding arithmetic expressions in bash.
I have a variable that contains a two digit number, for example 54 or
03. I want to use this variable in an arithmetic expression, something
like:
x=$((100*MyVar/MaxValue))
The problem ocurs when MyVar is less than 10, because 03, for example,
is considered an octal number. That works fine anyway in most cases,
but 08 and 09 does not, of course.
So I need some way to filter those initial zeroes out from MyVar:
01 → 1
02 → 2
and so on.
x=$(echo 08 | sed 's/^0*\([^0]*\)/\1/')
echo $x
8
So far, so good.
However, 00 → 0 seems to be a problem:
x=$(echo 00 | sed 's/^0*\([^0]*\)/\1/')
echo $x
(x is an empty string).
Maybe sed isn't the best tool for this, but what is? Is there a ”trim
number from inital zeroes” function available, perhaps?
Kind regards
Johnny Rosenberg
ジョニー・ローゼンバーグ
More information about the ubuntu-users
mailing list