Bash: How to List All Files Matching a Specific Pattern


Often you may want to list all files in a folder that match a specific pattern using Bash.

You can use the following methods to do so:

Method 1: List All Files Containing String

ls *this_string*

Method 2: List All Files that Start with String

ls this_string*

Method 3: List All Files that End with String

ls *.txt

Method 4: List All Files that Contain One of Several Strings

ls | grep -i -E 'string1|string2'

The following examples show how to use each of these methods in practice with the following directory on our computer:

  • c:/users/bobbi/data3

We can use the ls command to view all files in this folder:

Example 1: List All Files Containing String Using Bash

We can use the following syntax to list all files in the current folder that contain the string “players” anywhere in the file name:

ls *players*

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

Bash list all files matching pattern

Note that this returns the following files:

  • new_players.txt
  • players.txt

Notice that both of these files contain the string “players” in the file name.

Example 2: List All Files that Start with String Using Bash

We can use the following syntax to list all files in the current folder that start with the string “new” in the file name:

ls new*

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

Bash list all files that start with pattern

Note that this returns the following files:

  • new_coaches.txt
  • new_managers.csv
  • new_players.txt

Notice that each of these files starts with the string “new” in the file name.

Example 3: List All Files that End with String Using Bash

We can use the following syntax to list all files in the current folder that end with the string “.txt” in the file name:

ls *.txt

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

Bash list all files that end in pattern

Note that this returns the following files:

  • conference.txt
  • new_coaches.txt
  • new_players.txt
  • players.txt

Notice that each of these files ends with the string “.txt” in the file name.

Example 4: List All Files that Contain One of Several Strings

We can use the following syntax to list all files in the current folder that contain either “new” or “players” in the file name:

ls | grep -i -E 'new|players'

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

Bash list all files that contain one of several patterns

Note that this returns the following files:

  • new_coaches.txt
  • new_managers.csv
  • new_players.txt
  • players.txt

Notice that each of these files contains either the string “new” or “players” in the file name.

Related Tutorials

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

Bash: How to List All Files in Folder by Size
Bash: How to List All Files in Folder Without Extension
Bash: How to Delete All Files in Directory

Leave a Reply