Find files containing multiple strings

纵饮孤独 提交于 2019-12-30 11:23:32

问题


I use a command to recursively find files containing a certain string1:

find . -type f -exec grep -H string1 {} \;

I need to find files containing multiple strings, so the command should return those containing all strings. Something like this:

find . -type f -exec grep -H string1 AND string2 {} \;

I couldn't find a way. The strings can be anywhere in the files. Even a solution for only two strings would be nice.


回答1:


you can also try this;

find . -type f -exec grep -l 'string1' {} \; | xargs grep -l 'string2'

this shows file names that contain string1 and string2




回答2:


with GNU grep

grep -rlZ 'string1' | xargs -0 grep -l 'string2'


from man grep

-r, --recursive

Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option.

-Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters.




回答3:


You can chain your actions and use the exit status of the first one to only execute the second one if the first one was successful (omitting the operator between primaries defaults to -and):

find . -type f -exec grep -q 'string1' {} \; -exec grep -H 'string2' {} \;

The first grep command uses -q, "quiet", which returns a successful exit status if the string was found.




回答4:


Answer

As you can see from the other answers on this page, there are several command-line tools that can be used to perform conjunctive searching across files. A fast and flexible solution that has not yet been posted is to use ag:

ag -l string1 | xargs ag -l string2

Useful variations

For case-insensitive searching, use the -i option of ag:

ag -il string1 | xargs ag -il string2

For additional search terms, extend the pipeline:

ag -l string1 | xargs ag -l string2 | xargs ag -l string3 | xargs ag -l string4


来源:https://stackoverflow.com/questions/39850672/find-files-containing-multiple-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!