Course outline · 0% complete

0/29 lessons0%

Course overview →

Wildcards and find

lesson 4-2 · ~9 min · 11/29

Wildcards: patterns for file NAMES

The payoff of this lesson is acting on groups of files in one command — back up every .png, delete every .tmp — and, with find, locating a file you know exists somewhere in a big project without clicking through directories.

grep searches inside files. To match file names, the shell gives you wildcards (also called globs):

  • * matches any run of characters: *.txt means every name ending in .txt
  • ? matches exactly one character: photo?.png matches photo1.png but not photo10.png
  • [ab] matches one character from the set: report[12].txt

Key mental model: the shell expands the pattern before the command runs. When you type ls *.txt, ls never sees the star. The shell rewrites it to ls draft.txt notes.txt first. Wildcards work with any command: cp *.png backup/, rm *.tmp, grep todo *.md.

*.txtthe shell expands this pattern…notes.txtdraft.txtphoto.pngscript.sh✓ match✓ match✗ skipped✗ skipped…so ls *.txt actually runs asls draft.txt notes.txt
The shell, not the command, resolves wildcards. The command receives the already-expanded list of names.

Code exercise · bash

Run it. Five files, two patterns: * grabs all .txt files, ? matches the single digit in photoN.png.

find: search the whole tree

Wildcards only look in the current directory. find walks a directory and all its subdirectories:

find . -name "*.txt"
find . -type d
  • The first argument is where to start (. = here, from lesson 2-1).
  • -name "*.txt" filters by name. The quotes matter: they stop the shell from expanding the star early, so find itself gets the pattern.
  • -type d finds directories only, -type f files only.

find prints results in whatever order it walks the tree, so in the example we pipe into sort for a predictable order (pipes get the full treatment in unit 5).

Code exercise · bash

Run it. find digs guide.txt out of docs/ even though we never cd there, then lists every directory in the tree.

Quiz

Which pattern matches chapter1.md and chapter2.md but NOT chapter10.md?

Code exercise · bash

Your turn. The starter builds a music/ tree with two .mp3 files buried in subdirectories plus one .png. Use find (piped into sort) to list only the .mp3 files. Expected output: ``` ./music/jazz/song2.mp3 ./music/rock/song1.mp3 ```