Bash – cat * | grep something… what file is the result in

bashcatgrep

If one was to run the following command

cat * | grep DATABASE

the shell would spit out all the lines in * files that contained the word DATABASE in them. Is there any way to also spit out what file each line is apart of?

I tried to use the -H option for grep which according to man says print the filename for each match but in my shell it just says

(standard input):$DATABASE_FUNCTION = dothis();

Best Answer

Don't use cat for that. Instead use grep DATABASE * or grep -n DATABASE * (if you want to know the line numbers as well as the filenames) directly.

See useless use of cat.

To clarify a bit more: cat * actually concatenates all files as it feeds them to grep through the pipe, so grep has no way of knowing which content belongs to which file, and indeed can't even really know if it's scanning files or you're just typing mighty fast. It's all one big standard input stream once you use a pipe.

Lastly, -H is redundant almost for sure as grep prints the filename by default when it's got more than one file to search. It could be of some use in case you want to parse the output, though, as there's some possibility the * glob will expand to a single file and grep would in that case omit the filename.

Related Topic