Best examples of zgrep and zcat commands in Unix/Linux

In Linux and Unix, we have a grep command used to search for a given string in log and text files.

Suppose you have uncompressed files like gzip, tar gz files, How do you search for a given word in those search files?

Tomcat server stores the daily log files in tar.gz format. If you want to search for errors or strings in those files, We can use zgrep for search and zcat to view the files.

This post covers the following examples

  • Find the given input string in tar.gz files
  • Search string in nested folder contains gzip files
  • search tar files for a given string
  • how to use grep command on gz files.

grep command does not work on tar or gz files, It is an equivalent command called zgrep.

Here is the syntax of the Zgrep command

zgrep searchpattern inputgzdirectory options

searchpattern is any plain string or combination of *,? and plainstring

inputgzdirectory is the location of gz files

options are optional like -R or -M

How to search tar.gz files for a given string without extracting it?

In a directory, there are many tar.gz files, how do we search for a particular word in those files? one solution is to unzip the .gz file and use the grep command.

Here are the steps

gunzip filename.gz
grep "searchword" file

The other and better solution is using the zgrep command in Unix.

zgrep -a "search word" filename.gz

grep command works on text files and zgrep works on compressed logs.

How to Search gzip files in a nested folder

zgrep search in the current directory gz files.

If you want to search nested and recursive folders/directories, use the -R option.

zgrep -R --include=*.gz -H "*Exception*" .

Zcat command example in Linux

Cat command in Linux is used to view the log and text files,

Zcat is similar to the cat command but it only works with tar/gz files.

The Zcat command is used to view compressed files in Linux or Unix.


zcat options gzfile

It is used to view compressed files without uncompressing them.

zcat filename.tar.gz

you can also use the pipe symbol to move content to other files or the console.

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.