grep is a good device for looking by way of information and customary enter in Linux and is ready to match string and Regex patterns. Nevertheless, generally it’s mandatory to manage what sorts of information
grep searches for, and it has flags inbuilt to do exactly that.
Solely Together with Sure Information in grep Searches
grep will search all information in a given folder and its subfolders for those who invoke it with the recursive
-r flag. This may decide up every thing, however for those who solely need sure extensions, the choice you’ll need to use is
--include flag tells
grep to solely embody information 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, similar to wildcards to match every thing together with a sure extension:
grep -inr --include *.txt "foo" ~/folder
Be aware that that is escaped with a ahead slash
as a result of it’s potential for filenames to have asterisks in them. It’s also possible to specify a number of
--include flags, for instance, looking all HTML, JS, and CSS supply information in a wwwroot:
grep -inr --include *.html --include *.css --include *.js "foo" ~/folder
You’ll be able to equally additionally exclude sure file names, which is able to nonetheless match every thing apart from the glob, performing as a blacklist on prime of the present configuration:
grep -inr --exclude *.txt "foo" ~/folder
There’s additionally a flag to exclude whole directories without delay:
grep -inr --exclude-dir config "foo" ~/folder
Utilizing discover As a substitute
Alternatively, for those who want utilizing the
discover utility to go looking by way of information, you possibly can join it to
grep utilizing pipes and
discover can do looking with patterns and Regex, and has a number of benefits, together with with the ability to filter information simply based mostly on metadata like dimension, date created and modified, and different Linux identifiers.
The command is a bit 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"