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
To access the last character of a string, we can use the parameter expansion syntax ${string: -1} in the Bash shell. In bash the negative indices count from the end of a string, so -1 is the index of a last character. Note: Space is required after the colon (:); otherwise it doesn't work.
with grep : the * means: "match 0 or more instances of the preceding match pattern (which is [^ ] ), and the $ means "match the end of the line." So, this matches the last word after the last space through to the end of the line; ie: abc.
All you need is grep -Eo '[0-9]+$'
:
gv@debian:~$ echo 234ef85 |grep -Eo '[0-9]+$' ## --> 85
gv@debian:~$ echo 234ef856 |grep -Eo '[0-9]+$' ## --> 856
gv@debian:~$ echo 234ef85d6 |grep -Eo '[0-9]+$' ## --> 6
gv@debian:~$ echo 234ef85d.6 |grep -Eo '[0-9]+$' ## --> 6
gv@debian:~$ echo 234ef85d.6. |grep -Eo '[0-9]+$' ## --> no result
gv@debian:~$ echo 234ef85d.6.1 |grep -Eo '[0-9]+$' ## --> 1
gv@debian:~$ echo 234ef85d.6.1222 |grep -Eo '[0-9]+$' ## --> 1222
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 lineIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With