Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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();
share|improve this question
    
good question. I'm still trying to break the cat -> grep habit myself. :) –  Sirex Jun 30 '11 at 6:52

2 Answers 2

up vote 16 down vote accepted

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.

share|improve this answer

Use grep -H DATABASE * (note: if there's more than one file in the directory, the -H is optional).

The problem you're having is that with your command, cat * concatenates all of the files together into one big mess, and then | sends that into the standard input of grep DATABASE. By the time grep sees the data, the info about where it came from has been lost. The solution is to have grep do the work of looking through the individual files, so when it find a match it knows which file it came from.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.