Bash: How to Find Newest File Matching a Pattern


Often you may want to find the newest file that matches a pattern in a specific directory in Bash.

You can use the following syntax to do so:

find . -name "*2024*" -print0 |
    xargs -r -0 ls -1 -t |
    head -1

This particular example will return the newest file in the current directory that contains the pattern “2024” in the filename.

Here is what the various commands do:

  • find . -name “*2024*” -print0: Print all files matching the pattern “2024” in the current directory
  • xargs -r -0 ls -l -t: Return all files sorted by last modification time ( -t ) and return nothing ( -r ) if there are no matching files
  • head -1: Only return file with most recent modification time

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

Example: Find Newest File Matching a Pattern in Bash

Suppose that we would like to find the newest file in our current directory that contains the pattern “2024” in the filename.

Before we do so, we can use the ls -l command to first view all files along with their latest modification time in our current directory:

The output displays each of the filenames along with their latest modification time in our current directory.

We can see that there are three filenames with the pattern “2024” in the name.

We can use the following syntax to return only the newest filename that contains this pattern:

find . -name "*2024*" -print0 |
    xargs -r -0 ls -1 -t |
    head -1

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

Bash find newest file matching pattern

This returns the file named rosters2024.csv.

By viewing the previous output from the ls -l command we can confirm that this is indeed the newest file with the pattern “2024” in the filename.

Feel free to replace “2024” with any other pattern that you would like to match.

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 by Date
Bash: How to List All Files in Folder Without Extension

Leave a Reply