How to Find All Files With an Extension in Bash

Sheeraz Gul Feb 15, 2024
How to Find All Files With an Extension in Bash

This tutorial demonstrates how to find all files with an extension in Bash.

Find All Files With an Extension in Bash

Finding files with a particular extension is an easy operation in Bash. We can use the find command and the -name option to find the files with a particular extension.

Syntax:

find DirectoryPath -type f -name '*.txt'

The above command can get the files with the txt extension from the given directory. We can put . for the current directory or directory path; the -type f will select only files, not folders, and -name will be used to get a particular extension.

Now let’s try an example from a particular directory; first, let’s see the directory structure in the following animation:

Directory Structure

As we can see, the directory contains subfolders containing some files. Let’s try to run an example now.

find /mnt/c/Users/Sheeraz/DemoFolder1 -type f -name '*.txt'

The above command will get all the files with txt extensions, even from the subfolders. See the output:

/mnt/c/Users/Sheeraz/DemoFolder1/delftstack1.txt
/mnt/c/Users/Sheeraz/DemoFolder1/delftstack2.txt
/mnt/c/Users/Sheeraz/DemoFolder1/delftstack3.txt
/mnt/c/Users/Sheeraz/DemoFolder1/demo.txt
/mnt/c/Users/Sheeraz/DemoFolder1/SubFolder/delftstack1.txt
/mnt/c/Users/Sheeraz/DemoFolder1/SubFolder/delftstack2.txt
/mnt/c/Users/Sheeraz/DemoFolder1/SubFolder/delftstack3.txt
/mnt/c/Users/Sheeraz/DemoFolder1/SubFolder/demo.txt
/mnt/c/Users/Sheeraz/DemoFolder1/SubFolder1/delftstack1.txt
/mnt/c/Users/Sheeraz/DemoFolder1/SubFolder1/delftstack2.txt
/mnt/c/Users/Sheeraz/DemoFolder1/SubFolder1/delftstack3.txt
/mnt/c/Users/Sheeraz/DemoFolder1/SubFolder1/demo.txt

As we can see, the command looked for the txt files and returned all the text files in the directory. This command can be used with any extension; let’s try to use it with another extension.

find /mnt/c/Users/Sheeraz/DemoFolder1 -type f -name '*.rtf'

This command will look for the files with the RTF extension. See the output:

/mnt/c/Users/Sheeraz/DemoFolder1/delftstack.rtf
/mnt/c/Users/Sheeraz/DemoFolder1/SubFolder/delftstack.rtf
/mnt/c/Users/Sheeraz/DemoFolder1/SubFolder1/delftstack.rtf

As we can see, the command successfully returns all the files with a particular extension.

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Bash Find