Removing initial zero from variables

Johnny Rosenberg gurus.knugum at gmail.com
Sat Feb 18 19:20:43 UTC 2012


Den 18 februari 2012 20:05 skrev Johnny Rosenberg <gurus.knugum at gmail.com>:
> Den 18 februari 2012 19:54 skrev Johnny Rosenberg <gurus.knugum at gmail.com>:
>> 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
>> ジョニー・ローゼンバーグ
>
> Found it, I think:
> $ echo 00 | bc
> 0
> $ echo 000008 | bc
> 8
> $
>
> I'm not sure if there are any drawbacks yet, though…
>
>
> Kind regards
>
> Johnny Rosenberg
> ジョニー・ローゼンバーグ

Oh… and here is a better one:
~$ MyVar=0008
~$ x=$((100*$[10#$MyVar]/12))
~$ echo $x
66
~$

”$[10#$MyVar]” forces bash to use decimal representation.


Kind regards

Johnny Rosenberg
ジョニー・ローゼンバーグ




More information about the ubuntu-users mailing list