Grep Compressed .gz Files At A Shell Prompt

Posted on in Categories , , , last updated December 2, 2013

I am a new Unix/Linux shell user and I have lots of .gz files in my directory. I would like to search .gz files using the grep command. Unfortunately, grep command is not working on my compressed files. How do I write a script to automate entire procedure to grep some compressed files? Do I have to uncompress them first and run grep over them?

No you don’t have to uncompress files using gunzip or gzip command. Linux and UNIX-like operating systems comes with z* commands. You need to use zgrep command which invokes grep on compressed or gzipped files. All options specified are passed directly to the grep command or egrep command.

Syntax

To search .gz file called test.gz, enter:
$ zgrep 'word-to-search' /path/to/test.gz
$ zgrep 'GET /faq/a-long-url/' /path/to/access.log.gz

You can run zcat command to display file on screen:
$ zcat file.gz

See a list of all z-commands on Unix-like operating system for more information.

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Leave a Comment