【问题标题】:Print file name in front of grep matched pattern output lines在 grep 匹配的模式输出行前面打印文件名
【发布时间】:2019-04-03 22:16:10
【问题描述】:

我想将匹配模式的行内容从输入文件打印到输出文件。我正在使用:

    grep -hnr "pattern" ./input.txt > output.txt 

Output.txt 文件如下:

this line has the word pattern in it 

但我想在输出文件的同一行中打印输入文件的名称。例如,我希望输出文件是这样的:

input this line has the word pattern in it 

如果模式在输入文件中多次匹配,我想多次打印文件名。例如:

input this line has the word pattern in it 
input this line also has same pattern

最后,我想在一个包含许多输入文件(*.txt 格式)的目录中执行此操作,并生成一个包含所有结果的 output.txt 文件。

【问题讨论】:

  • 就做grep -hnr pattern ./*.txt。如果列出多个输入文件,grep 默认会打印匹配的文件名。
  • 所有 UNIX 工具都有手册页。 man grep.

标签: linux shell awk sed


【解决方案1】:

只需使用:

 grep -H "pattern" ./input.txt > output.txt 

来自man grep

-H, --with-filename
打印每个匹配的文件名。当有多个文件要搜索时,这是默认设置。

-h, --no-filename
抑制输出文件名的前缀。当只有一个文件(或只有标准输入)要搜索时,这是默认设置。

【讨论】: