Linux zgrep FAQ: How do I use the Linux
zgrep command? (Or, How do I grep a GZ file?)
Linux users quickly learn how to use the Linux
grep command on plain text files, but it takes a little longer to really you can grep gzip (gz) files as well. Here's how.
Problem - Want to grep gzip files
You want to grep a text file that has been compressed with
gzip. You typically use the following steps to grep a gzip'd file, but you know there must be a better way:
gunzip myfile.gz grep foo myfile gzip myfile
Solution: the zgrep command
Unix and Linux systems come with a modified version of
zgrep. The Linux
zgrep command works just like the
grep command, except it works on text files that have been compressed with the gzip command.
This means that instead of following the three-step process shown above, you can just use zgrep to search a compressed text file in one step, like this:
zgrep foo myfile.gz
As another example, the
zgrep command also works great on compressed Apache log files. For instance, if I want to see the hits on this blog in a gzip'd Apache log file, I'd use a
zgrep command like this:
zgrep 'GET /blog' access_log.gz
or more likely I'd pipe the output into the Linux more command, like this:
zgrep 'GET /blog' access_log.gz | more
As you can see, using the
zgrep command is much easier than using the three-step gunzip/grep gzip command I showed at the beginning of this article.