How can I get the last number from string in bash?

Viewed 14859

Sorry, I'll explain it better

How can I get the last number from string?

Examples of generics strings:

If str=str1s2
echo $str | cmd? 
I get 2

If str=234ef85
echo $str | cmd? 
I get 85

 If str=djfs1d2.3
echo $str | cmd? 
I get 3

"cmd?" is the command/script that I want

7 Answers

Get all numbers from a string:

grep -Eo '[0-9]+'

Get last number from a string:

grep -Eo '[0-9]+' | tail -1

(Expanding on George's answer a bit..)

  • -E means extended regex
  • -o means print each matching part on a separate line

No need to spawn a child process, since you have regexp matching in bash. Assume for example the string

str=a34b56c

Now you can do

if [[ $str =~ ([0-9]+)[^0-9]*$ ]]
then
  echo The last number is ${BASH_REMATCH[1]}
else
  echo The string "$str" does not contain digits
fi

The trick here is putting parenthesis around that part of the pattern which makes up the number. This allows you to pick up the number using ${BASH_REMATCH[1]}.

Related