Bash: How to Extract Last Number from a String


Often you may want to use Bash to extract the last number in a particular string.

You can use the following syntax to do so:

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

This particular example will extract the last number from the string stored in the variable named my_string.

Here is what the various commands do:

  • grep: Used to extract a matching pattern
  • -E: Specifies an “extended” regex pattern
  • -o: Specifies that only the matching pattern should be returned
  • [0-9]+: Used to match one or more digits
  • tail -1: Returns only the last matching digits

The following example shows how to use this syntax in practice.

Example: How to Extract Last Number from a String in Bash

Suppose we have the following string that represents the employee ID for a manager at a particular company:

  • Manager1430Department15

Suppose that we would only like to extract 15, which represents the last  number in this string.

We can use the following syntax to do so:

my_string="Manager1430Department15"
echo $my_string | grep -Eo '[0-9]+' | tail -1

The following screenshot shows how to use this syntax in practice:

Bash extract last number from string

Notice that this returns 15, which represents the last number in the string.

Note that if you’d like to only extract the single last digit in a string, you can leave out the + sign after the [0-9] as follows:

my_string="Manager1430Department15"
echo $my_string | grep -Eo '[0-9]' | tail -1

The following screenshot shows how to use this syntax in practice:

Bash extract single last digit in string

Notice that this returns 5, which represents the single last digit in the string.

Feel free to use whichever method you prefer, depending on your end goal.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Check if String Starts with Specific Value
Bash: How to Check if String Contains Substring
Bash: How to Remove First and Last Characters from String

Leave a Reply