Command line find
is a powerful, underutilized tool. In this post, I’ll go through the following use cases:
- Find files by name
- Find files by file extension
- Find recently modified files
- Delete files using find
Find files by name
I use this all the time. Let’s say I’m in my ~/Downloads
directory. That directory has several hundred files in it—and quite a few subdirectories—so it’s a bit hard to comb through in a GUI. I misplaced my favicon
files in there, so I’ll use find
:
find . -name "favicon*"
# Here's why I couldn't find em, they're in a subdirectory
# ./dev_site/favicon_io
# ./dev_site/favicon_io/favicon-16x16.png
# ./dev_site/favicon_io/favicon.ico
# ./dev_site/favicon_io/favicon-32x32.png
The search above was for all files starting in my current directory (.
) whose names start with “favicon”. Find also has -iname
for case-insensitive filename search.
Find files by file extension
This is really just another flavor of finding by name, where the file extension is part of the name:
# Find all csv files
find . -name "*.csv"
# ./data/states/MN.csv
# ./data/states/AZ.csv
# ./data/summaries/N00047871.csv
# ./data/summaries/N00001373.csv
You’ll notice above that find
searches directories recursively by default, which is handy. There is a way to limit the depth, but I rarely need it and won’t cover it here. To learn more, try this link and look for -maxdepth
.
Find recently modified files
I use this version less frequently than finding by name, but it still comes in handy:
# Find all files with "last modified" time in the last 3 days
# Note it is negative 3
find . -mtime -3
The ls
command is also very useful for finding recently modified files; the -t
flag will order your results by last modified time. For example, this command will give you the 5 most recently modified files in a directory: ls -t | head -n 5
Delete files using find
No need to use xargs, find has a built-in delete option:
# BE CAREFUL: find will do this recursively by default
find . -name "filename.csv" -delete
# If you're unsure about your directories, use maxdepth
find . -name "filename.csv" -maxdepth 1 -delete
Earlier I mentioned that find
searches directories recursively by default. Usually I think that’s a good thing, but when deleting it could come back to bite you. If you’re deleting with find
and you’re not 100% sure about the directory structure underneath you, you might want to pass in a -maxdepth
flag to stop find
from going too far into subdirectories.
That’s it! Find has a lot more options, but I rarely use anything other than what’s described above. If you want to dive deeper, the helpful link below has a ton of information.
Helpful Links