Unix/Linux zgrep FAQ: How do I use the Linux zgrep
command? (Also asked as, “How do I grep a gzip file?”, or “How do I search a gz file?”)
Problem: You want to grep gzip files
You want to grep a text file that has been compressed with gzip
. For instance, you are currently using the following steps to grep a gzip'd file, but you know there must be a better way:
gunzip myfile.gz # unzip the file grep foo myfile # search the resulting file with grep gzip myfile # gzip the file back to its previous state
Short Solution: Use zgrep to search gz files
The solution is to use the grep
command to search plain text files, and use zgrep
to search gz
(gzip’d) files. Here’s a short example:
zgrep 'my string' my_file.gz
Read on for more details.
Solution: the zgrep command
Unix and Linux systems come with a modified version of grep
named 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.