Bash: How to Find First Folder Name that Contains String


Often you may want to use Bash to find the first folder name in a directory that contains a specific string.

You can use the following syntax to do so:

find . -maxdepth 1 -type d -name '*old*' -print -quit

This particular example will return the first folder name that contains the string “old” in the current directory.

Here is what the various commands do:

  • find . -maxdepth 1: Return all items in current directory (not in subfolders)
  • -type d: Only return directories (not files)
  • -name ‘*old*’: Only return directories that contain the string “old”
  • -print -quit: Only print the first folder name (“quit” after finding it)

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

Example: How to Find First Folder Name that Contains String in Bash

Suppose we would like to find the first folder name in the current directory that contains “old” in the name.

First, we can use the following syntax to view all items in our current directory:

ls -l

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

From the output we can see that there are six folders in the current directory:

  • managers
  • new_athletes
  • new_coaches
  • old_athletes
  • old_coaches
  • owners

Suppose that we would like to find the first folder name in the directory that contains “old” in the name.

We can use the following syntax to do so:

find . -maxdepth 1 -type d -name '*old*' -print -quit

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

Bash find first folder name that contains string

This returns ./old_athletes, which is indeed the first folder name that contains “old” in the name.

Note #1: Feel free to leave out the -quit argument if you would like to return all folder names that contain “old” in the name.

Note #2: Feel free to replace “*old*” with any other string that you would like to search for in your own folder names.

Related Tutorials

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

Bash: How to Count Number of Folders in a Directory
Bash: How to Find the Largest File in a Directory
Bash: How to Check if Specific File Type Exists in Directory

Leave a Reply