根據文件包含字串搜尋多個文件

根據文件包含字串搜尋多個文件

假設我有一個包含電子郵件的文字文件

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 的選項,該選項不可移植。

相關內容