Find files: find and grep -r
Find files by name with find -name, by type with -type, and search inside many files with grep -r. Practise on a deep project folder in your browser.
Somewhere in a project there's a file you need, and you don't remember where. find walks through a directory and every directory inside it, and prints the paths that match:
find projects -name "*.md"The first argument is where to start (. for here); after it come the tests:
| Test | Matches |
|---|---|
-name "pattern" | names matching the pattern (* and ? work) |
-iname "pattern" | the same, ignoring case |
-type f | files only |
-type d | directories only |
-maxdepth 1 | stop one level down |
Tests combine: find projects -type d -name "s*" lists directories starting with s.
Tip:Quote the pattern. Unquoted, the shell expands *.md in the current directory first, and find gets the wrong question (or an error saying "paths must precede expression").
Searching inside files
find looks at names. To look inside files, use grep with -r (recursive), which searches every file under a directory:
grep -r TODO projects-l prints only the names of the files that match, which is handy when the matching lines are long.
Your turn
Find the file named config.yml somewhere under projects and cd into the directory that holds it. Then list the files under projects that contain TODO.
Your task
Find the file named config.yml somewhere under projects and cd into the directory that holds it. Then list the files under projects that contain TODO.
- Go to the directory that holds config.yml (not done yet)
- List the files that contain TODO (not done yet)
The checklist ticks itself off as you work in the terminal: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
find -name- The file name matches PATTERN (* ? and [ ] work as in the shell) More on find →
find -type- Only names of one type: f for files, d for directories More on find →
grep -r- Search every file in a directory and the folders inside it More on grep →
grep -l- Print only the names of files that have a match More on grep →