Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

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

like image 713
Phocs Avatar asked May 20 '17 19:05

Phocs


People also ask

How do I get the last character in Bash?

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.

How do I get the last word of a string in Linux?

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.


2 Answers

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
like image 162
George Vasiliou Avatar answered Oct 28 '22 07:10

George Vasiliou


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
like image 38
Vojtech Vitek Avatar answered Oct 28 '22 05:10

Vojtech Vitek