📃 Cheatsheet
List all files and folders in current directory:
find
Find files/folders that match a pattern:
find -name "*pattern*"
Run a command per result. Substitute command
with your actual command.
find . -name "*pattern*" -exec command {} +;
What is find?
find
is a command I rarely come across but it turns out, it’s one of the more powerful commands in Unix-like system. Find, at its basest, lists all the files and folders in a directory. Kind of like a recursive ls
. This can be piped into any command. But find also has other features like filtering and the ability to execute a command on each matching file.
Find is also sometimes used as the “backend” for fuzzy file searchers. For example, fzf
uses find
under the hood to employ fuzzy search in the command line (which is super useful).
Plain “find”
Using find
alone will print out all directories and files located under your current working directory. This is useful for piping or other actions.
find
Just for the sake of completeness, you can also specify a path but find
will assume you want to search your current directory by default.
find /path/to/dir
Find file or directory by pattern
To find a file or directory, one can specify its name and pass it in as an argument. Both files or directories will match.
find -name "package.json"
find -name "node_modules"
Find will return any matches including nested directories. Note that the match isn’t done on the path but on the actual directory/file name itself.
You can also specify a pattern using *
as a wildcard like so:
find -name "pattern*"
find -name "*.spec.js"
Execute a command on all found files
find
allows you to execute logic on every single match it finds via the -exec
flag. There are 2 ways to execute commands: once on all the results or run it per result.
Here’s once for all results:
# substitute any kind of command for the keyword "command"
find . -name "*.js" -exec command {} ;
The command has several parts. We’re already familiar with the pattern matching so next comes the -exec
flag. After exec
, you can type out your command and end it with \;
. The {}
braces will be substituted with the find
results.
To run the command separately per result, end your command with +
instead of \;
.
# substitute any kind of command for the keyword "command"
find . -name "*.js" -exec command {} +