Bash: How to Use Regex to Match Digits


Often you may want to use Regular Expressions in Bash to match digits in strings.

You can use the following methods to do so:

Method 1: Match Digits Using [0-9]

grep -E '[0-9]' employees.txt

This particular example will return all lines in the file named employees.txt that contain numeric digits anywhere in the line.

Method 2: Match Digits Using [[:digit:]]

grep -E '[[:digit:]]' employees.txt

This particular example will also return all lines in the file named employees.txt that contain numeric digits anywhere in the line.

Note that the -E operator specifies that you’re using an extended regular expression.

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

Example: How to Use Regex to Match Digits in Bash

Suppose that we have a text file named employees.txt that contains employee ID values for various employees at some company.

We can use the cat command to view the contents of this file:

Suppose that we would like to return only the lines from the file that contain numeric digits somewhere in the line.

One way to do so is by using grep with the pattern [0-9] as follows:

grep -E '[0-9]' employees.txt

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

Bash regex match digits

Notice that this returns only the lines from the file that contain numeric digits somewhere in the line.

Note: If you only want to match certain digits then you can specify them within the brackets. For example, you could use [0-3] to only match lines that contain 0, 1, 2 or 3.

Another way to only return the lines that contain numeric digits is by using grep with the pattern [[:digit:]] as follows:

grep -E '[[:digit:]]' employees.txt

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

Bash match digits in string

Notice that this also returns only the lines from the file that contain numeric digits somewhere in the line.

Feel free to use whichever method you prefer.

Related Tutorials

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

Bash: How to Use Regex with “OR” to Match Multiple Patterns
Bash: How to Replace Patterns Using Regex
Bash: How to Use find -exec with grep

Leave a Reply