Working with files
Linux commands: find
Learn how the Linux find command searches recursively for files and folders by name, type, size, or age, and runs a command on each match with -exec.
The find command finds files or folders matching a search pattern. It searches recursively, so it looks inside every subfolder of the place you start from.
Let’s learn it by example.
Find all the files under the current tree that have the .js extension, and print the relative path of each match:
find . -name '*.js'
./src/index.js
./src/lib/api.js
The . is where the search starts: the current folder. Each result is a path relative to it.
Use quotes around special characters like *. Without them, the shell expands *.js to the matching names in the current folder before find runs, and things break in confusing ways. With main.js and app.js in the current folder, this is what you get:
find . -name *.js
find: main.js: unknown primary or operator
find received app.js main.js instead of the pattern, and doesn’t know what to do with the second one. Quote the pattern and the problem disappears.
Find directories under the current tree matching the name “src”:
find . -type d -name src
Use -type f to search only files, or -type l to only search symbolic links.
-name is case sensitive. Use -iname for a case-insensitive search.
You can search under multiple root trees:
find folder1 folder2 -name filename.txt
Find directories under the current tree matching the name “node_modules” or “public”:
find . -type d -name node_modules -or -name public
You can also exclude a path, using -not -path:
find . -type d -name '*.md' -not -path 'node_modules/*'
You can search files that have more than 100 characters (bytes) in them:
find . -type f -size +100c
Search files bigger than 100KB but smaller than 1MB:
find . -type f -size +100k -size -1M
Search files edited more than 3 days ago:
find . -type f -mtime +3
Search files edited in the last 24 hours:
find . -type f -mtime -1
You can delete all the files matching a search by adding the -delete option. This deletes all the files edited in the last 24 hours:
find . -type f -mtime -1 -delete
Be careful with -delete. My habit is to run the search without it first, read the list, and only then add -delete to the same command. There is no confirmation and no trash bin.
You can execute a command on each result of the search. In this example we run cat to print the file content:
find . -type f -exec cat {} \;
Notice the terminating \;. It marks the end of the command to run, and it’s escaped so the shell doesn’t treat ; as the end of the whole line. {} is filled with the file name at execution time.
If building the right find command feels like a puzzle, I made a find command builder that puts it together for you.
Lesson completed