Unix ‘grep’ for a string within all gzip files in all subdirectories

grepunix

How do I grep for a string recursively through all .gz files in all directories and subdirectories?

Best Answer

@Steve Weet is almost there. The use of /dev/null as an additional argument is a nice way to force the filename to be shown (I'll remember that, thanks Steve) but it still runs the exec for every file found -- a huge overhead.

You want to run zgrep as few times as you can, getting the most out of each execution:

find . -iname '*.gz' -print0 | xargs -0 zgrep PATTERN

xargs will supply as many args (filenames) as possible to zgrep, and repeatedly execute it until it has used all the files supplied by the find command. Using the -print0 and -0 options allows it to work if there are spaces in any of the file or directory names.

On Mac OS X, you can achieve the same effect without xargs:

find . -iname '*.gz' -exec zgrep PATTERN {} +
Related Question