Grep 顯示找到的檔名和字串

Grep 顯示找到的檔名和字串

我需要一個egrep命令來列出包含單字+它找到的字串的所有檔案名稱。讓我們想像一下這個場景:

我需要找到的單字:applewatermelonbanana

我需要什麼:我想列出包含其中任何一個的所有文件(不需要將所有文件放在同一個文件中),並列印在文件中找到的單字。我想要的搜尋結果範例:

./file1.txt:apple
./file1.txt:banana
./file2.txt:watermelon
./file5.txt:apple

我記得在搜尋結果中看到一個grep命令FILENAME:STRING,但我不記得它是如何完成的。我試過:

egrep -lr 'apple|banana|watermelon' .

但搜尋結果顯示:

./file1.txt
./file2.txt

好的,它有幫助,但是......在 中file1,它找到了哪一個單字?這就是我面臨的問題。

答案1

您使用了-l,這與您想要的相反。從man grep:

-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.)

你想要的是-H

-H, --with-filename
      Print the file name for each match.  This is  the  default  when
      there is more than one file to search.

但這無論如何都是預設的。做就是了:

grep -Er 'apple|banana|watermelon' .

-E告訴我們grep要像 那樣行事egrep。)

答案2

使用 awk 的方法:

awk -v var1=apple -v var2=banana -v var3=watermelon '{ if($0~var1) {print FILENAME":"var1} ; if($0~var2) {print FILENAME":"var2} ; if($0~var3) {print FILENAME":"var3}  }' *

基本上,聲明 3 個變數和 3 個 if 語句來列印檔案名稱和已找到的對應變數

編輯

較短的版本:

awk '/watermelon/{ print FILENAME":watermelon" }; /banana/{print FILENAME":banana"}; /apple/ {print FILENAME":apple"}' *

基本想法是尋找/regular expression/並在找到後執行大括號中的程式碼(即列印 FILENAME 以及我們找到的字串)。

答案3

這是您要尋找的命令:

grep -R "apple\|banana\|watermelon" <search_path>

-R 會讀取每個目錄下的所有文件搜尋路徑,遞歸地。每場比賽都會顯示檔案名稱。

答案4

以下將為您提供所需的輸出(使用 bash):

for x in apple banana watermelon ; do grep $x * ; done

輸出將為您提供包含搜尋字串的所有行。

以下內容將僅提供搜尋字串作為輸出:

for x in apple banana watermelon ; do grep -l $x * |xargs -I{} echo {}:$x; done

相關內容