Finding files by name and content

Search is where it gets really interesting because we have so much power and things we can do after we've found a certain file. Let's look at the basic operations first, finding a file by its name, a pattern or its type. Also remember, we can always use the wildcard operator, globbing, and all the other goodies the CLI allows us to use.

command line
// Finding an exact match
find ./ -name "file1.txt"
← Back
Next →

Note that the matches above are case sensitive, unless we pass the parameter -iname instead of -name where i stands for case-insensitive. We'll later look at pipes and other operators that allow us to do even more things with our results than just displaying them. For now though, let's take a look at grep, one of the most powerful commands, which allows us to search the content of files and return a list of all files containing our search term or pattern.

Searching for content inside files from the CLI

Let's say we want to find every occurrence of weakMap in our JavaScript files and we know there are a bunch of those occurrences in our current project. We can utilize grep to look for all files containing the string weakMap

command line
grep "weakMap" *.js

Depending on our shell, the output will not be highlighted or provide otherwise helpful information, which is why it's good to know a few flags that we can pass with grep that make our results a little easier to read and more useful, such as adding the line numbers of each match.

command line
# --color (colorizes matches)
# -n (show line numbers)
# -C <number> (show N lines above/below match for context)
grep --color -n -C 5 "weakMap" *.js