🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Finding Files

Finding files means searching a folder tree for files that match a rule. The find command walks through folders and prints every path that matches.

Finding files by name

The pattern "*.txt" matches names that end in .txt. The readme file ends in .md, so find leaves it out.

mkdir notes
touch notes/apple.txt
touch notes/banana.txt
touch notes/readme.md
find . -name "*.txt" | sort

Listing folders only

The -type d flag asks find for folders. The current folder appears as a single dot at the top.

mkdir notes
mkdir docs
touch notes/apple.txt
touch docs/guide.txt
find . -type d | sort

Matching a different ending

Changing the pattern changes the matches. Now only the two files ending in .md are printed.

mkdir notes
mkdir docs
touch notes/apple.txt
touch notes/readme.md
touch docs/guide.md
find . -name "*.md" | sort

Example

mkdir notes
mkdir docs
touch notes/apple.txt
touch notes/banana.txt
touch notes/readme.md
touch docs/guide.txt
echo "Text files:"
find . -name "*.txt" | sort
echo "Folders:"
find . -type d | sort

Key points

  • find starts at the folder named after it and searches below it.
  • A dot after find means the current folder.
  • Use -name with a quoted pattern to match file names.
  • The pattern sits in quotes, so the shell leaves it alone and find does the matching.
  • Use -type d to list folders instead of files.
  • find prints each match as a path that starts with ./
  • Piping find output into sort gives a steady A to Z listing.

In this example, the script builds two folders and four files inside them. The first find lists every text file in the whole tree. The second find lists the folders, starting with the current folder as a dot.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which command lists all files ending in .txt under the current folder?