简体   繁体   中英

Print file name in front of grep matched pattern output lines

I want to print line content of a matched pattern from a input file to a output file. I am using:

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

Output.txt file is like:

this line has the word pattern in it 

But I want to print name of the input file in the same line in output file. For example, I want the output file to be like:

input this line has the word pattern in it 

If the pattern matches multiple times in input file, I want to print filenames multiple times. For example:

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

and finally, I want to do this in a directory with many input files (*.txt format) and generate one output.txt files with all results.

Simply use :

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

From man grep :

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

-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM