1. Introduction

The find command in Linux is a versatile tool for searching and locating files and directories within a directory hierarchy. In addition, this command is particularly valuable for system administrators and users who need to automate file-related tasks or efficiently manage large sets of files.

In this tutorial, we’ll discuss how to stop the find command after the first match.

First, we’ll discuss built-in options available in the find command. Next, we’ll explore the use of the head command in combination with find. After that, we’ll discuss leveraging text-processing commands. Lastly, we’ll discuss a loop-based approach.

2. Sample Directory

Let’s first use the tree command to take a look at the sample directory we’ll work on:

tree
.
├── dir1
│   ├── image1.jpg
│   ├── imageA.jpg
│   ├── pyhtonGame.py
│   ├── pythonCal.py
│   └── pythonFunc.py
|__ picArt.png
|__ picCamp.png
|__ gifCat.gif
|__ gifDuck.gif
├── dir2
│   ├── findFile.sh
│   ├── findText.sh
│   ├── findColor.sh
│   ├── fileWeb.html
│   └── filePage.html
│   └── driverAUX.zip
└── driverUSB.zip
└── devApp.js
└── devCart.js
└── file1.txt
└── file2.txt
└── file3.txt
2 directories, 21 files

Within the current structure, we have a main directory with two subdirectories, each containing diverse files types.

3. Using Built-in find Options

In this section, we’ll go over different find options that can aid us with our goal of getting only the first match of a given search.

3.1. Basic Command

To begin with, let’s discuss the find command to search for a file within a directory tree.

For example, let’s execute find to get a Bash file from the dir2 directory:

$ find /home/ubuntu/dir2 -name "find*.sh" -print
/home/ubuntu/dir2/findFile.sh
/home/ubuntu/dir2/findText.sh
/home/ubuntu/dir2/findColor.sh

Here, we see that by using the find command without any flags or additional specifications, the names of all the matched files in that particular directory are printed on the terminal.

3.2. Using find With –quit

Now, we’ll discuss how we use the find command with the –quit flag to stop the search after we search the first match.

For instance, to get the first Bash script file that starts with find from the directory dir2, we use the -quit option to get the first file that matches the search result:

$ find /home/ubuntu/dir2 -name "find*.sh" -print -quit
/home/ubuntu/dir2/findFile.sh

In the above code, we used a wildcard with the find command which searches for an .sh file in the path /home/ubuntu/dir2. Here, we use the -name flag to search the files by name. Notably, this is case-sensitive.

Next, the –print flag instructs find to print the path of the searched file to the standard output. After that, the -quit flag ensures that the search stops after it detects the first match. Once the code detects a match, it also prints the file path.

4. Using find With the head Command

To stop find after the first match, we can pipe the output of the find command to head:

$ find /home/ubuntu/dir2 -name "file*.html" | head -n 1
/home/ubuntu/dir2/filePage.html

The above code utilizes the find and head commands with a wildcard to search for HTML files with a name starting with file within the directory /home/ubuntu/dir2. Next, the find command generates a list of all matching files. After that, the output is piped to the head command.

Furthermore, the -n 1 option instructs head to display only the first line of the output, effectively showing the path of the first file that matches the specified criteria.

5. Leveraging Text Processing Tools

We can also leverage various text processing commands with find to search for particular files. Therefore, in this section, we’ll go through awkgrep, and sed.

5.1. Using find With the awk Command

Consequently, we use the awk command with find to get a file name that matches only the first occurrence.

For instance, to search for a .png file, we’ll pipe the result from find to awk:

$ find /home/ubuntu/dir1 -name "pic*.png" | awk 'NR==1 {print; exit}'
/home/ubuntu/dir1/picArt.png

This code utilizes the find and awk commands together with a wildcard to search for filenames that start with pic. In this process, the find command initiates the search for a file with the specified name. Subsequently, we pipe the output to the awk command.

Within the awk command, the condition NR==1 ensures that subsequent actions are applied only to the first line of input. Furthermore, the instruction {print; exit} directs the program to print the path of the initial matching file and subsequently halt any further processing.

5.2. Using find With grep

An alternative way to find a file with a specific name, then stop at the first searched file and exclude the rest is to use the grep command.

For example, we’ll search for a zip file:

$ find /home/ubuntu/dir2 -name "driver*.zip" | grep -m 1 ''
/home/ubuntu/dir2/driverUSB.zip

The above code is a combination of commands that combine the find and grep commands to locate a file name within the designated directory. In particular, we use the find command to generate a list of files matching the specified name, and then we pipe this output to the grep command.

The above code is a combination of commands that utilize the find and grep utilities:

  • find generates a list of files matching the specified name
  • the output of find is piped to the grep command

Moreover, the grep command, with the options -m 1 and an empty pattern, stops the search process after the first line.

5.3. Using find With the sed Editor

Additionally, we can use the sed editor to find the file that matches first and exclude other results:

$ find /home/ubuntu/dir2 -name "file*.txt" | sed -n '1p;q'
/home/ubuntu/dir2/file2.txt

The above command combines find and sed to search for files with a specific name.

The find command generates a list of matching files and then pipes the output to the sed command. After that, the sed command selectively prints the first line of the input to the path of the first matching file and then quits, effectively preventing further processing.

Let’s break down the -n ‘1p;q’ options:

  • -n suppresses the default behavior of printing every line
  • 1p prints the first line of the input
  • ; separates commands in sed
  • q quits processing after it prints the first line

Thus, the combination of find and sed provides a concise and flexible way to manipulate and print the first match to the standard output.

6. Using a Loop and the find Command

Alternatively, we can use shell scripts with loops and find to search for the first instance of a file with a specific name in the directory tree.

Let’s suppose we want to get the first instance of a JavaScript file that starts with dev:

$ cat loop.sh
#!/bin/bash
while IFS= read -r file; do
    echo "$file"
    break
done < <(find /home/ubuntu/dir2 -name "dev*.js")

Now, let’s make the file executable using the chmod command, and run the script:

$ chmod +x loop.sh
$ ./loop.sh
/home/ubuntu/dir2/devApp.js

The above Bash script locates a file that starts with dev within the /home/ubuntu/dir2 directory using the find command. Specifically, we use a while loop to iterate through the output of the find command, printing each file path to the terminal.

Furthermore, we use the read command to read input from the find command line by line:

  • IFS= ensures that the code preserves the leading and trailing whitespaces
  • -r prevents backslashes from being treated as escape characters

Afterward, the break statement ensures that the loop exits after processing the first file path. In addition, we use command substitution to feed the output of the find command as input to the while loop.

In summary, the script prints the path of the first file named devApp.js , and then exits. By using the while loop to read the output of the find command line by line, we can employ the break statement to ensure that the code processes only the first line.

7. Conclusion

In this article, we learned how to stop the find command after the first match.

Initially, we discussed the options available with the find command. After that, we investigated the head command that we can pipe with find to achieve the desired result.

Moreover, we explored various text editors that provided us with similar results. Lastly, we touched on the subject of loops.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.