0

Okay so I'm using grep on a external HDD

example,

M:/

grep -rhI "bananas" . > out.txt

which would output any lines within " M:/ " containing " bananas "

However I would like to output the entire contents of the file, so if one line in example.txt contains " bananas " output entire content of example.txt and same goes for any other .txt file within directory " M:/ " that contains " bananas ".

user3255841
  • 113
  • 1
  • 2
  • 8
  • 1
    Have you thought to use the '-l' option for grep to output filenames and you pipe this command with 'xargs cat' ? It will output the content of all your files. At least, it works on Linux. – FrenchieTucker Jun 30 '17 at 16:27

1 Answers1

1

To print the contents of any file name containing the string bananas would be:

find . -type f -exec grep 'bananas' -l --null {} + | xargs -0 cat

The above uses GNU tools to handle with file names containing newlines.

Forget you ever saw any grep args to recursively find files, adding those args to GNU grep was a terrible idea and just makes your code more complicated. Use find to find files and grep to g/re/p within files.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    I'm curious: why quote the `{}`? For consistency, it seems this ought to be `xargs "-0" "cat" "{}"` – William Pursell Jun 30 '17 at 18:04
  • 1
    But I think you just want `xargs -0 cat` in any case. – William Pursell Jun 30 '17 at 18:07
  • The quotes are just being over-cautious since I don;t use that command much so don't know for SURE how it behaves when the file name contains globbing chars and white space. You're right though I dont need the `{} at all so removing it now, thx. – Ed Morton Jun 30 '17 at 19:57