Search My Techie Guy

Thursday, October 14, 2021

How to grep a zipped file (.gz) without having to first unzipp it

Summary:

In this post, we are going to quickly look at a command to help us grep a zipped file (.gz format) without having to first unzipp it.

Problem or Goal: 

Well in most cases, system logs quickly grow very big and they are archived as zipped files (.gz format). We tend to always find ourselves in situation where we have to search and analyze archived logs when troubleshooting or doing fault analysis or preparing RCA reports. 
This command saves us the time to quickly grep through .gz archives without having to gunzip them, it also saves on the system resources because unzipping a file will consume disk space and cpu.

Cause:

Let's quickly look at apache "access_log" on my webserver:

# cd /var/log/apache2
# ls -ltr

At the moment, the access_log is not archived and i can easily cat and grep



Now am going to archive this file using "gzip" command and attempt to "cat and grep", i will use the gzip command that keeps the original file and creates a compressed copy. 

# gzip -c access_log > access_log.gz

# ls -ltr





Now let's attempt the "cat and grep"



Oops! it's returning nothing!

Solution: 

The solution is to use the "zcat" magic command instead of "cat"

Problem Solved?

Let's see



Yes we have output, it did the magic, we can grep a zipped file without having to first unzip it. 
Cheers.