cat * | grep something... what file is the result in?

12,888

Solution 1

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.

Solution 2

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:
12,888

Related videos on Youtube

Jake Wilson
Author by

Jake Wilson

Updated on September 18, 2022

Comments

  • Jake Wilson
    Jake Wilson over 1 year

    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();
    
    • Sirex
      Sirex almost 13 years
      good question. I'm still trying to break the cat -> grep habit myself. :)