Bash: How to Extract First Number from a String


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

You can use the following syntax to do so:

echo $my_string | sed -E 's,^[^0-9]*([0-9]+).*$,\1,'

This particular example will extract the first number from the string variable named my_string.

Note that if a number in a string contains a decimal point then this syntax will extract only the number before the decimal point.

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

Example: How to Extract First 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 1430, which represents the first number in this string.

We can use the following syntax to do so:

employee_ID="Manager1430Department15"
echo $employee_ID | sed -E 's,^[^0-9]*([0-9]+).*$,\1,'

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

Bash extract first number from string

Notice that this returns 1430, which represents the first number in the string.

Suppose instead that we had the following string:

  • Manager1430.552Department15

We can use the same syntax to extract the first number before the decimal place from the string:

employee_ID="Manager1430.552Department15"
echo $employee_ID | sed -E 's,^[^0-9]*([0-9]+).*$,\1,'

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

Bash extract first number before decimal in string

Notice that this returns 1430, which represents only the first number before the decimal place in the employee ID.

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 Count Number of Words in String
Bash: How to Count Number of Characters in String

Leave a Reply