根据文件包含字符串搜索多个文件

根据文件包含字符串搜索多个文件

假设我有一个包含电子邮件的文本文件

abd3@dom
abd2@dom
sdklf2@lksd
sd@gm

我需要 grep 、 find 的小 bash 脚本来查找文件中包含的电子邮件,并打印出它们匹配的文件。

期望它是

**this email abd3@dom found in file8560.txt**
**this email abd2@dom found in file750.txt**
**this email sdklf2@lksd found in file970.txt**
**this email sd@gm found in file2690.txt**

答案1

如果您知道要在其中搜索电子邮件地址的文件列表,则可以

grep -F -H -w -o -f email_list_file list of files to search | awk -F: '{print "*** this email " $2 " found in " $1 "**}'

'-w' 标志将减少但并不能消除埃德在评论中指出的一些误报。打印需要“-o”标志仅有的电子邮件地址,而不是包含该地址的整行。

答案2

grep -Fxf list_of_emails.txt files...

find ... -type f -exec grep -Fxf list_of_emails.txt /dev/null {} +

...将命令中的替换find为文件和目录列表以及其他find谓词。

/dev/null是为了强制grep始终在结果中添加文件名前缀,而 grep 在使用单个文件调用时不会执行此操作。这模拟了-HGNU grep 的选项,该选项不可移植。

相关内容