Bash: How to Remove Non-Numeric Characters from String


Often you may want to use Bash to remove non-numeric characters from a string.

There are two common ways to do so:

Method 1: Use Pure Bash

new_var=${old_var//[!0-9]/

This particular example will remove all non-numeric characters from the string variable named old_var and save the results to a new variable named new_var.

Method 2: Use sed

new_var=$(echo $old_var | sed 's/[^0-9]*//g')

This particular example will also remove all non-numeric characters from the string variable named old_var and save the results to a new variable named new_var.

The following example shows how to use each of these methods in practice.

Example: How to Remove Non-Numeric Characters from String

Suppose we have the following string stored in a variable named id_number in Bash:

  • HH5469JY

Suppose that we would like to remove all non-numeric characters so that we are left with the following string:

  • 5469

One way to do so is by using the following syntax with pure Bash:

id_number="HH5469JY"

new=${id_number//[!0-9]/}

echo $new

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

Bash remove non-numeric characters from string

Notice that when we use the echo statement to view the new variable named new we can see that it contains the following string:

  • 5469

All of the non-numeric characters have been removed from the string.

Note that we could also use the following syntax with sed to achieve the same results:

id_number="HH5469JY"

new=$(echo $id_number | sed 's/[^0-9]*//g')

echo $new

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

Bash remove non-numeric characters from string using sed

Notice that when we use the echo statement to view the new variable named new we can see that it contains the following string:

  • 5469

Feel free to use whichever method you prefer to remove all non-numeric characters from your own string.

Related Tutorials

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

Bash: How to Remove Specific Characters from String
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