Grep 显示找到的文件名和字符串

san*_*998 3 grep

我需要一个 egrep 命令来列出所有包含单词 + 找到的字符串的文件名。让我们想象一下这个场景:

我需要找到的单词:apple,watermelonbanana

我需要什么:我想列出包含其中任何一个的所有文件(不需要将所有文件都放在同一个文件中),并打印它在文件中找到的单词。我想要的搜索结果示例:

./file1.txt:apple
./file1.txt:banana
./file2.txt:watermelon
./file5.txt:apple
Run Code Online (Sandbox Code Playgroud)

我记得在搜索结果中看到过一个grep命令FILENAME:STRING,但我不记得它是如何完成的。我试过:

egrep -lr 'apple|banana|watermelon' .
Run Code Online (Sandbox Code Playgroud)

但搜索结果显示:

./file1.txt
./file2.txt
Run Code Online (Sandbox Code Playgroud)

好的,它有帮助,但是 ... in file1,它找到了哪个词?这就是我面临的问题。

mur*_*uru 14

您使用了-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.)
Run Code Online (Sandbox Code Playgroud)

你想要的是-H

-H, --with-filename
      Print the file name for each match.  This is  the  default  when
      there is more than one file to search.
Run Code Online (Sandbox Code Playgroud)

但无论如何,这是默认设置。做就是了:

grep -Er 'apple|banana|watermelon' .
Run Code Online (Sandbox Code Playgroud)

-E告诉grep要表现得像egrep。)

  • @ user2576376 那么你在错误的网站上问这个问题。在 [unix.se] 上询问。 (5认同)
  • @user2576376 只需使用`grep -Ero 'apple|banana|watermelon'。` (2认同)