This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.
Last Updated: 2024-11-21
Although tools like rg
are faster, find
is still indispensible due to portability. You write the script once on your machine and then share it with your team or with all developers using your library.
The basic command is
find starting_path
e.g.
find .
This lists all files in dir and subdirectory
You can filter with a name parameter
find . -name "package.json"
The other thing to remember is that the command-line flags, when though full words, use a single dash - -maxdepth
not --maxdepth
This prevents find from going way too deep, e.g. into tested node module folders
Depth of 1 is current folder. 2 is one folder deep
Thus this command might be used in a node mono-repo that contains top-level subfolder projects with their own package.json
files
find . -name "package.json" -type f -maxdepth 2
Say you just want files backup
as opposed to folders
find . -name "backup" -type f -maxdepth 2
Find is exact match only for the file name (path does not matter)
Thus if the relative path is ./git/search-in-git-history.md
and I run find . -name search-in-git
there will be zero results, owing to the lack of the .md
at the end.
Fix with
# !!!!! When using globs, it MUST be in quotes
find . -name "search-in-git*"
# Case insensitive
find . -iname "SEARCH-in-git*"
Put a -not
before the -name
(etc. ) bit
find . -not -name "*.md" -type f
List all files modified in last 3 days
find . -mtime -3
List all files modified in last 3 hours
find . -mtime -3h
find . -size +10000k
# Use minus for smaller than
find . -size -10000k
Find is quite vocal about permissions errors. This can break certain programs.
find / -name tnsnames.ora 2>/dev/null
find . -type d
find . -type f
find . -type l
find /home -user jack
find . -type f -name "*.mp3" -exec rm -f {} \;
There is also -delete
shorthand
find . -type f -name "*.mp3" -delete
Accessed in last 2rr hours
find . -atime 0