10

I have a string like rev00000010 and I only want the last number, 10 in this case.

I have tried this:

TEST='rev00000010'
echo "$TEST" | sed '/^[[:alpha:]][0]*/d'
echo "$TEST" | sed '/^rev[0]*/d'

both return nothing, although the regex seems to be correct (tried with regexr)

16

The commands you passed to sed mean: if a line matches the regex, delete it. That's not what you want.

echo "$TEST" | sed 's/rev0*//'

This means: on each line, remove rev followed by any number of zeroes.

Also, you don't need sed for such a simple thing. Just use bash and its parameter expansion:

shopt -s extglob         # Turn on extended globbing.
echo "${TEST##rev*(0)}"  # Remove everything from the beginning up to `rev`
                         # followed by the maximal number of zeroes.
5

POSIXly:

test='rev00000010'
number=${test#"${test%%[1-9]*}"}

Would remove every thing to the left of the left-most non-zero digit.

Bournely/universally:

number=`expr "x$test" : 'xrev0*\(.*\)'`
  • The first will break with dots, hex, spaces, etc: test='rev 003A0.1056' will produce number="3A0.1056". The second will break on any space, the same value will produce: 003A0.1056 from the expr. – user79743 Aug 10 '15 at 6:03
3

If you already have the variable TEST just print it with all letter removed

printf "%.0f\n" ${TEST//[a-z]/}

or

printf "%g\n" ${TEST//[a-z]/}

Do not use %d or echo-command becouse numbers with leading 0 is understood as octal

2

A few more options (though I also recommend you use Parameter Expansion as suggested by @choroba):

  • Use sed or perl to replace everything but the last two characters with the last two characters. This effectively deletes everything except the last two.

    $ sed -r 's/.*(..)/\1/' <<<$TEST
    10
    $ perl -pe 's/.*(..)/\1/' <<<$TEST
    10
    
  • Set awk's field delimiter to 2 or more 0s and print the last field:

    $ awk -F"00+" '{print $NF}' <<<$TEST
    10
    
  • Extract only the last two characters:

    $ grep -oP '..$' <<<$TEST
    10
    $ perl -lne '/(..)$/; print $1' <<<$TEST
    10
    
  • Print only the 10th-last bytes:

    $ cut -b 10- <<<$TEST
    10
    

Note that all of the above use <<<$var which is a bash construct. To use it in other shells, change to echo "$TEST" | command.

  • 1
    For awk other variant which can avoid some problem awk -F"[a-z]" '{print +$NF}' – Costas Nov 13 '14 at 14:54
0

To get the "last number", select any sequence of digits at the end of the string, and convert it to a decimal number:

With Bash:

 [[ "$test" =~  ([1-9][0-9]*)$ ]] && echo "number: $((10#${BASH_REMATCH[1]}))"

With grep:

echo "$test" | grep -Po "[1-9][0-9]*$"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.