Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 18 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


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.