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

You can use parameter expansion with extglob. First, remove the number from the end, then remove what you got from the beginning.

#!/bin/bash
shopt -s extglob
for str in str1s2 djfs1d2.3 fefwfw4rfe45 234ef8 ; do
    without_number=${str%%+([0-9])}
    echo ${str#$without_number}
done

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

Tags:

Linux

Shell

Bash