Removal of insignificant zeros from a variable

Solved
Hello,

I'm following up on a similar request made a while ago. I'm experiencing the same issue (I want to remove the insignificant leading zeros from an alphanumeric variable that contains only digits).
I copied exactly the example that was given back then.
If I apply the recommended solution directly from the command line, it works.

>var=0000001253; echo ${var##*(0)}
1253


However, as soon as I put it into a shell script, I do not get the expected result at all:
>cat test.sh


#!/bin/bash var=0000001253; echo ${var##*(0)}


>test.sh
0000001253


Well, I'm on CentOS7 Linux. It must be something simple. Maybe I'm missing something....

Thanks for your replies

Configuration: CentOS Linux release 7.5.1804 (Core)

5 answers

  • Votes
  • Date
  • Descending date
  1. Contributor
    $ cat test.sh
    #!/bin/bash
    shopt -s extglob
    var=0000001253; echo ${var##*(0)}
    $ test.sh
    1253
    $
    1. Moderator
      Hello,

      Indeed it doesn’t work. You can remove the leading zeros with
      sed
      :

      #!/bin/bash var=0000001253 var=$(echo $var | sed -e "s/^0*//") echo $var


      Good luck
      1. Hello,

        Yes, that works. Thank you very much. But still, I would like to understand why the direct command isn't working in the script...
    2. Contributor
      hello
      do not execute the script by:
      sh test.sh
      1. Hello,

        Um!!! But how do I run the script then? In any case, I wasn't running it with sh test.sh, but just test.sh...
    3. Hello,

      Yep! It works with shopt too. Thanks a lot. I don't know what this shopt is. I'll look into it.
      1. Contributor
        in the bash man page, see
        Filename Expansion
        ....
        If the extglob shell option is enabled using the shopt command, several extended pattern matching operators are recognized. ...