LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   About trimming a variable (https://www.linuxquestions.org/questions/linux-newbie-8/about-trimming-a-variable-739666/)

ahmedb72 07-13-2009 01:29 AM

About trimming a variable
 
Hi,
When I studied variable or parameter expansions, I learned the following:

${variable%pattern} trim the shortest match from the end
${variable%%pattern} trim the longest match from the end
I couldn't figure out the difference between them.

Code:

#var1=1100
#echo ${var1%0}
110
#echo ${var1%%0}
110

Thanks in advance.

Disillusionist 07-13-2009 01:59 AM

Try:

echo ${var1%0*}

echo ${var1%%0*}

ahmedb72 07-13-2009 05:08 AM

Hi Disillusionist,
Your code example illustrated for me the difference but it violated the trimming purpose. I simply want to trim the leading zeros. eg: 1100 -> 11 , 210 -> 21

Code:

#var1=11001
#echo ${var1%0*}
110                    <--- no trimming
#echo ${var1%%0*}
11


colucix 07-13-2009 05:36 AM

The wildcard * has the bash meaning, not the regexp one. In parameter substitution
Code:

${var%%0*}
it means any character from zero to the end of the string. In your first example, instead, the pattern matched just one zero, so that using either %% or % the result is the same. If you want to remove any number of trailing zeros you have to activate the extglob option:
Code:

$ var=1100
$ shopt -s extglob; echo ${var%%+(0)}; shopt -u extglob

See man bash under the section pathname expansion --> pattern matching for details.


All times are GMT -5. The time now is 11:51 AM.