Find command

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-04-25

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

Tip: Use 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

Tip 2: Use types to filter files/dirs

Say you just want files backup as opposed to folders

find . -name "backup" -type f -maxdepth 2

Tip 3: Learn how its globs work

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*"

Tip 4: Do negation

Put a -not before the -name (etc. ) bit

find . -not -name "*.md" -type f

Tip 5: Do multiple clauses

Tip 6: Limit to modified in last N days / last N hours

List all files modified in last 3 days

find . -mtime -3

List all files modified in last 3 hours

find . -mtime -3h

Tip 7: Find all files larger than 10,000kb

find . -size +10000k
# Use minus for smaller than
find . -size -10000k

Tip: 8 You may want to send error to dev/null

Find is quite vocal about permissions errors. This can break certain programs.

find / -name tnsnames.ora 2>/dev/null

Tip 9: Filter to just files/folders/sym links

find . -type d
find . -type f
find . -type l

Tip 10: Search by user

find /home -user jack

Tip 11: Execute another command on each result

find . -type f -name "*.mp3" -exec rm -f {} \;

There is also -delete shorthand

find . -type f -name "*.mp3" -delete

Tip 11: Find by last access time

Accessed in last 2rr hours

find . -atime 0