简体   繁体   English

bash:检查目录中的多个文件是否包含列表中的字符串

[英]bash: check if multiple files in a directory contain strings from a list

Folks, 民间,

I have a text file which contains multiple lines with one string per line : 我有一个文本文件,其中包含多行,每行一个字符串:

str1
str2
str3

etc.. 等等..

I would like to read every line of this file and then search for those strings inside multiple files located in a different directory. 我想读取此文件的每一行,然后在位于不同目录的多个文件中搜索那些字符串。

I am not quite sure how to proceed. 我不太确定如何进行。

Thanks very much for your help. 非常感谢您的帮助。

Use the GNU Grep's --file Option 使用GNU Grep的--file选项

According to grep(1): 根据grep(1):

   -f FILE, --file=FILE
          Obtain  patterns  from  FILE,  one  per  line.   The  empty file
          contains zero patterns, and therefore matches nothing.   (-f  is
          specified by POSIX.)

The -H and -n flags will print the filename and line number of each match. -H-n标志将打印每个匹配项的文件名和行号。 So, assuming you store your patterns in /tmp/foo and want to search all files in /tmp/bar, you could use something like: 因此,假设您将模式存储在/ tmp / foo中并想在/ tmp / bar中搜索所有文件,则可以使用类似以下内容的方法:

# Find regular files with GNU find and grep them all using a pattern
# file.
find /etc -type f -exec grep -Hnf /tmp/foo {} +
for wrd in $(cut -d, -f1 < testfile.txt); do grep $wrd dir/files* ; done
awk 'NR==FNR{a[$0];next} { for (word in a) if ($0 ~ word) print FILENAME, $0 }' fileOfWords /wherever/dir/*
while read -r str
do
   echo "$str"
   grep "$str" /path/to/other/files
done < inputfile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM