Grep Compressed .gz Files At A Shell Prompt

last updated in Categories , , ,

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, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Share this on (or read 0 comments/add one below):