I'm looking for the string foo=
in text files in a directory tree. It's on a common Linux machine, I have bash shell:
grep -ircl "foo=" *
In the directories are also many binary files which match "foo=". As these results are not relevant and slow down the search, I want grep to skip searching these files (mostly JPEG and PNG images). How would I do that?
I know there are the --exclude=PATTERN
and --include=PATTERN
options, but what is the pattern format? The man page of grep says:
--include=PATTERN Recurse in directories only searching file matching PATTERN.
--exclude=PATTERN Recurse in directories skip file matching PATTERN.
Searching on grep include, grep include exclude, grep exclude and variants did not find anything relevant
If there's a better way of grepping only in certain files, I'm all for it; moving the offending files is not an option. I can't search only certain directories (the directory structure is a big mess, with everything everywhere). Also, I can't install anything, so I have to do with common tools (like grep or the suggested find).
Try this one:
Founded here: http://www.unix.com/shell-programming-scripting/42573-search-files-excluding-binary-files.html
I'm a dilettante, granted, but here's how my ~/.bash_profile looks:
Note that to exclude two directories, I had to use --exclude-dir twice.
ripgrep
This is one of the quickest tools designed to recursively search your current directory. It is written in Rust, built on top of Rust's regex engine for maximum efficiency. Check the detailed analysis here.
So you can just run:
It respect your
.gitignore
and automatically skip hidden files/directories and binary files.You can still customize include or exclude files and directories using
-g
/--glob
. Globbing rules match.gitignore
globs. Checkman rg
for help.For more examples, see: How to exclude some files not matching certain extensions with grep?
On macOS, you can install via
brew install ripgrep
.Please take a look at ack, which is designed for exactly these situations. Your example of
is done with ack as
because ack never looks in binary files by default, and -r is on by default. And if you want only CPP and H files, then just do