Wildcards and finding files
Typing file names one by one doesn't scale. Wildcards (globs) let one pattern match many files, and find searches whole folder trees.
Wildcards (globbing)
| Pattern | Matches |
|---|---|
* |
Any number of characters (including none) |
? |
Exactly one character |
[abc] |
One character from the set |
[0-9] |
One digit |
The shell expands wildcards before running the command. ls *.jpg actually runs ls photo1.jpg photo2.jpg. You can see this with echo:
When nothing matches, the pattern is left as-is (in bash).
Wildcards work with every command
⚠️ Wildcards +
rm= danger.rm *deletes everything in the folder, andrm * .txt(note the space!) deletes everything, then complains that.txtdoesn't exist. Runlswith the same pattern first to preview what will be deleted.
Hidden files and wildcards
* doesn't match hidden files (names starting with .):
find: search a folder tree
Wildcards only look in one folder. find searches recursively through every subfolder:
| Option | Meaning |
|---|---|
find PATH |
Where to start searching (. = here) |
-name "pattern" |
Match the file name (quote the pattern!) |
-iname "pattern" |
Match the name, ignoring case |
-type f / -type d |
Only files / only directories |
-size +10M |
Bigger than 10 MB (real machines) |
-mtime -7 |
Modified in the last 7 days (real machines) |
-exec cmd {} \; |
Run a command on each result (real machines) |
Why quote the pattern? Without quotes, the shell would expand
*.mdin the current folder beforefindeven sees it. Quoting passes the pattern tofindso it can search every folder.
Real-world find recipes
find . -name "*.log" -mtime +30 -delete # delete logs older than 30 days
find . -name "node_modules" -type d -prune # locate bulky node_modules folders
find . -type f -size +100M # find huge files eating your disk
find src -name "*.js" -exec wc -l {} + # count lines in all JS fileslocate and fd
locate filenamesearches a prebuilt index of your whole disk, so it's instant (runupdatedbto refresh the index).fdis a modern, faster, friendlierfind(fd "\.md$"). It's worth installing.
Practice
- List all
.txtfiles inDocumentsusing a wildcard. - Use
findto locate every.shfile under your home folder. - Find all directories inside
projects. - Copy every file in
datawhose name ends in.txtor.loginto a new folder~/backup, using wildcards.
1.What does ls photo?.jpg match?
2.Why should you quote the pattern in find . -name "*.txt"?