我在一个有很多.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
Run Code Online (Sandbox Code Playgroud)-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.)
使用 GNU 工具:
grep -lZ stringA ./*.txt |
xargs -r0 grep -L stringB
Run Code Online (Sandbox Code Playgroud)
-L
、-Z
、-r
、-0
有时是 GNU 扩展,但并不总是在其他一些实现中找到。