grep
is a superb device for looking by means of recordsdata and normal enter in Linux and is ready to match string and Regex patterns. Nonetheless, typically it’s vital to manage what sorts of recordsdata grep
searches for, and it has flags in-built to just do that.
Solely Together with Sure Information in grep Searches
By default, grep
will search all recordsdata in a given folder and its subfolders when you invoke it with the recursive -r
flag. This can choose up every little thing, however when you solely need sure extensions, the choice you’ll wish to use is --include.
The --include
flag tells grep
to solely embody recordsdata matching a sure sample. If it’s specified, grep
will deal with all embody flags as a whitelist. You need to use this with any Linux glob characters, akin to wildcards to match every little thing together with a sure extension:
grep -inr --include *.txt "foo" ~/folder
Observe that that is escaped with a ahead slash as a result of it’s doable for filenames to have asterisks in them. You can too specify a number of
--include
flags, for instance, looking all HTML, JS, and CSS supply recordsdata in a wwwroot:
grep -inr --include *.html --include *.css --include *.js "foo" ~/folder
You may equally additionally exclude sure file names, which is able to nonetheless match every little thing aside from the glob, performing as a blacklist on high of the present configuration:
grep -inr --exclude *.txt "foo" ~/folder
There’s additionally a flag to exclude total directories directly:
grep -inr --exclude-dir config "foo" ~/folder
Utilizing discover As an alternative
Alternatively, when you choose utilizing the discover
utility to go looking by means of recordsdata, you possibly can join it to grep
utilizing pipes and xargs
. discover
can do looking with patterns and Regex, and has an a variety of benefits, together with with the ability to filter recordsdata simply based mostly on metadata like dimension, date created and modified, and different Linux identifiers.
The command is slightly obtuse, as you’ll want to make use of -print0
on the finish of discover
to print out a single line checklist, after which move it to xargs -0
and grep
from there.
discover ./ -type f -iname "*.txt" -print0 | xargs -0 grep "foo"