查找包含一个字符串但不包含另一个字符串的文件

Sof*_*mur 38 grep find files

我在一个有很多.txt文件的文件夹中,我想找到所有包含stringA但不包含的文件stringB(它们不一定在同一行)。有谁知道如何做到这一点?

Ber*_*ard 42

只要您的文件名不包含空格、制表符、换行符或通配符,并且如果您grep支持该-L选项,您可以按如下方式进行操作:

$ cat file1
stringA
stringC
$ cat file2
stringA
stringB
$ grep -L stringB $(grep -l stringA file?)
file1
Run Code Online (Sandbox Code Playgroud)

grep在子shell执行$(),将打印包含所有文件名stringA。这个文件列表是主grep命令的输入,它列出了所有不包含stringB.

man grep

  -v, --invert-match
          Invert the sense of matching, to select non-matching lines.  (-v is specified by POSIX.)

  -L, --files-without-match
          Suppress normal output; instead print the name of each input file from which no output would normally have been printed.  The scanning will stop on the first match.

  -l, --files-with-matches
          Suppress normal output; instead print the name of each input file from which output would normally have been printed.  The scanning will stop on the first match.  (-l is specified by POSIX.)
Run Code Online (Sandbox Code Playgroud)


Sté*_*las 6

使用 GNU 工具:

grep -lZ stringA ./*.txt |
  xargs -r0 grep -L stringB
Run Code Online (Sandbox Code Playgroud)

-L-Z-r-0有时是 GNU 扩展,但并不总是在其他一些实现中找到。