1

I want to search recursively for a certain word, say MyWord, but I want to print the entire contents of all files that contain MyWord. How do I do this?

It turns out that I particularly care about binary sqlite files, both grepping them, and reading the result as a text file, rather than binary.

muru
  • 197,895
  • 55
  • 485
  • 740
  • 1
    Are you sure you want to read the entire content of each matching file? judicious application of grep's context switches (-A, -B, -C) may be more useful – steeldriver Apr 18 '18 at 01:58

3 Answers3

1

You can also use find with grep:

find . -type f -exec grep -wq 'MyWord' {} \; -exec cat {} >> /path/to/outfile \;

This will find files containing the word "MyWord" recursively and quite as soon as first match found then redirect the whole file content to a new file.

αғsнιη
  • 35,660
1

I would use:

sudo grep -rIlZ --exclude=${HISTFILE##*/} --exclude-dir={boot,dev,lib,media,mnt,proc,root,run,sys,/tmp,tmpfs,var} '/' -e 'MyWord' | xargs -0 cat > MyOutputFile
  • Drop sudo if not looking in system directories.
  • Change (root directory) '/' to current directory '.' or specific directory ie '/home/me/stuff'
  • Remove mnt to include Windows files mounted under mnt.
  • Remove lib to include Linux source files
  • Excluding directories necessary for speed. See: `grep`ing all files for a string takes a long time
  • --exclude=${HISTFILE##*/} is necessary if you run the command a second time or if the search string MyWord has ever been used in a different command before. This prevents 5 thousand history lines ($HISTFILE) from being included.
  • -r recursive, I skip binary files, lZ outputs a zero byte after each file name instead of the usual newline. Null (zero byte) terminators necessary for perl -0, sort -z and xargs used to cat (print out) the file contents.
  • > MyOutputFile sends output to file instead of screen. Leave this off for output to screen.

Note: Missing from output is the file name, just the file content is listed.

0

If your folder are not so big try:

grep -rz '.*MyWord.*'  myfolder > output

if necessary add -a