在许多只有一部分感兴趣的文件中搜索丢失的字符串(目标文件)

时间:2019-02-07 13:51:44

标签: grep

我在一个目录中有1000多个文件,但是对我感兴趣的文件只有其中一半!我只想经常在这些文件中搜索某些内容。不幸的是,无法匹配FILENAME中的某些内容。 我唯一要做的就是匹配示例中始终在“我的兴趣”文件中始终显示的某些字符串:“ special” ..,并以某种方式列出这些文件,并仅在其中搜索某些内容。也许一些堆叠的grep命令?

我试图在所有文件中搜索缺少的字符串“ line4 ”:

grep -c 'line4' * | grep -P ':0$'
file2.log:0
file3.log:0
file4.log:0
file5.log:0

# -c count lines that match the string and grep zero ones..

例如,我们在一个文件夹中有5个文件:

ls -l
file1.log  # interesed file (always contains on some line word: "special")
file2.log  # interesed file (always contains on some line word: "special")
file3.log  # interesed file (always contains on some line word: "special")
file4.log  # NOT interesed file
file5.log  # NOT interesed file


cat file1.log 
line1
special
line2
line3
line4
line5

cat file2.log 
line1
line2
special
line3

cat file3.log 
line1
line2
special
line3
line5

cat file4.log 
line1
line2
line3
line5

cat file5.log 
line1
line2
line3
line5

结果应该仅为file2和file3,因为在感兴趣的文件中不包含唯一字符串“ special”和“ line4”一词:

file2.log
file3.log

2 个答案:

答案 0 :(得分:0)

您可以通过“合并”两个grep命令来做到这一点:

grep -wl special `grep -wvl line4 *`

内部grep将生成不包含字符串“ line4”的文件列表。外部grep将在第一个grep

生成的文件列表中搜索单词“ special”

答案 1 :(得分:0)

使用GNU awk作为ENDFILE和单词边界:

awk '/\<special\>/{x=1} /\<line4\>/{y=1} ENDFILE{if (x && y) print FILENAME; x=y=0}' *