Often you may want to use Bash to extract only the numbers from a filename.
You can use the following syntax to do so:
ls | grep -Eo "[0-9]+"
This particular example will extract only the numbers from each file in the current directory.
Here is what the various commands do:
- ls: List all items in current directory
- 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
The following example shows how to use this syntax in practice.
Example: How to Extract Numbers from Filename in Bash
We can use the ls command to first view all files in our current directory:

We can see that our current directory contains the following files:
- 304teams_east.txt
- 315teams_west.txt
- 320teams_north.txt
- 435teams_south.txt
Suppose that we would like to extract only the numbers from each filename such as 304, 320, 315 etc.
We can use the following syntax to do so:
ls | grep -Eo "[0-9]+"
The following screenshot shows how to use this syntax in practice:

Notice that this returns only the numbers from each filename:
- 304teams_east.txt -> 304
- 315teams_west.txt -> 315
- 320teams_north.txt -> 320
- 435teams_south.txt ->435
Note that if you’d like to only extract the numbers from specific types of files then you could specify those file extensions immediately after the ls command.
For example, you could use the following syntax to only extract numbers from .txt files in the current directory:
ls *.txt | grep -Eo "[0-9]+"
Feel free to replace *.txt with any specific file extension that you’d like.
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
