How to use grep frequently within certain file extensions

grep It is a great tool for searching standard files and inputs in Linux and is able to match String and Regex patterns. However, sometimes it is necessary to control file types grep It searches for, and has built-in flags to do so.

Include only certain files in grep . searches

by default, grep It will search all files in a given folder and its subfolders if you invoke it with File -r Science. This will capture everything, but if you only want certain extensions, the option you want to use is --include.

The --include science says grep to me Include only Files matching a specific pattern. if specified, grep It will treat all included flags as a whitelist. You can use this with any Linux glob . characterssuch as wildcards to match everything including a given extension:

grep -inr --include *.txt "foo" ~/folder

Note that this is skipped with a forward slash Because file names can contain asterisks. You can also select multiple files --include tags, for example, searching all HTML, JS and CSS source files in wwwroot:

grep -inr --include *.html --include *.css --include *.js "foo" ~/folder

You can also exclude some filenames, which will still match everything except glob , acting as a blacklist above the current configuration:

grep -inr --exclude *.txt "foo" ~/folder

There is also a flag to exclude whole directories at once:

grep -inr --exclude-dir config "foo" ~/folder

Using search instead

Alternatively, if you prefer to use a file find To search through files, you can connect it grep using tubes and xargs. find It can search using patterns and Regex, and has a number of advantages, including the ability to easily filter files based on metadata such as size, creation date, modification, and other Linux identifiers.

It’s a bit obtuse, as you’ll need to use it -print0 At the end of find To print a one-line list, then pass it to xargs -0 And the grep from there.

 find ./ -type f -iname "*.txt" -print0 | xargs -0 grep "foo"



(Visited 1 times, 1 visits today)

Related posts

Leave a Comment