Home > OS >  How to return only integers from a variable in Shell Script and discard letters and leading zeros?
How to return only integers from a variable in Shell Script and discard letters and leading zeros?

Time:10-22

In my shell script there is a parameter that comes from certain systems and it gives an answer similar to this one: PAR0000008. And I need to send only the last number of this parameter to another variable, ie VAR=8. I used the command VAR=$( echo ${PAR} | cut -c 10 ) and it worked perfectly. The problem is when the PAR parameter returns with numbers from two decimal places like PAR0000012. I need to discard the leading zeros and send only the number 12 to the variable, but I don't know how to do the logic in the Shell to discard all the characters to the left of the number.

CodePudding user response:

Edit Using grep To Handle 0 As Part Of Final Number

Since you are using POSIX shell, making use of a utility like sed or grep (or cut) makes sense. grep is quite a bit more flexible in parsing the string allowing a REGEX match to handle the job. Say your variable v=PAR0312012 and you want the result r=312012. You can use a command substitution (e.g. $(...)) to parse the value assigning the result to r, e.g.

v=PAR0312012
r=$(echo $v | grep -Eo '[1-9].*$')
echo $r

The grep expression is:

  • -Eo - use Extended REGEX and only return matching portion of string,
  • [1-9].*$ - from the first character in [1-9] return the remainder of the string.

This will work for PAR0000012 or PAR0312012 (with result 312012).

Result

For PAR0312012

312012

Another Solution Using expr

If your variable can have zeros as part of the final number portion, then you must find the index where the first [1-9] character occurs, and then assign the substring beginning at that index to your result variable.

POSIX shell provides expr which provides a set of string parsing tools that can to this. The needed commands are:

expr index string charlist

and

expr substr string start end

Where start and end are the beginning and ending indexes to extract from the string. end just has to be long enough to encompass the entire substring, so you can just use the total length of your string, e.g.

v=PAR0312012
ndx=$(expr index "$v" "123456789")
r=$(expr substr "$v" "$ndx" 10)
echo $r

Result

312012

This will handle 0 anywhere after the first [1-9].

(note: the old expr ... isn't the fastest way of handling this, but if you are only concerned with a few tens of thousands of values, it will work fine. A billion numbers and another method will likely be needed)

CodePudding user response:

This can be done easily using Parameter Expension.

var='PAR0000008'
echo "${var##*0}"
//prints 8
echo "${var##*[^1-9]}"
//prints 8
var="${var##*0}"
echo "$var"
//prints 8

var='PAR0000012'
echo "${var##*0}"
//prints 12
echo "${var##*[^1-9]}"
//prints 12
var="${var##*[^1-9]}"
echo "$var"
//prints 12
  • Related