Find all files containing a string or text on Linux and Mac
Sometimes on linux/unix computers, you will want to do a search for any files containing a particular string within it. This can be particularly useful when searching for specific things for a CI/CD pipeline.
Fortunately, it is not too hard in linux to do this with
Find all files which contain a particular string on Linux or Macg
Return the filename only
The below will find any file that contains the term 'html' in the '/views' directory. It will return only the file names.
grep -rl ./views -e 'html'
Return the text itself
Again, this will find any file containing the string 'html' in the '/views' directory. It will return the line which has that text in it.
grep -r ./views -e 'html'
Options for grep on Linux/Mac
You can string other options together, to get different results. When we say
-r, for example, we mean 'recursive' - i.e. it will search through every folder. When we write
-rl, this means essentially
-r -l, which means search recursively, and return only the file name.
Below is a list of all grep options or switches, which you can add to your query to get the results you need:
- -r - search recursively.
- -l - return only the file name.
- -i - ignore the case.
- -w - search only for words, i.e. not text within words. For example, if we search for 'html', then somehtmltext would not match..
- -n - returns the line number, but doesn't work with
- -s - suppress any error messages.
- -h - output the line itself, without the line number or file.
- -v - invert the search, i.e. searching for html with
-vwill return everything without html.
- -f - used to indicate a file you want to use which contains a regular expression.
- -x - match only if the whole lines only. This will only return for a search of html if that exists on its own line separately.
More Tips and Tricks Linux
- Find all files containing a string or text on Linux and Mac
- Speed up your Website by Converting your Images to WebP from Terminal
- How to count all files in a directory in Linux
- Reference: Non Printable Characters List
- How the cd command works in Linux
- How the mv Command works on Linux
- How the chown Command works on Linux
- How to make a Symbolic Link on Linux
- How to Rename Files in Linux and MacOS Terminal
- How the alias Command works on Linux