It can be beneficial sometimes to search for patterns in files on a Linux server that have been compressed with gzip instead of having to uncompress each file to search through it. A good example of this if typically in log rotation you rotate the logs and compress the older log files so if you are troubleshooting an issue and need to search for an error in older log files you could use the method below to search the compressed log files to match a pattern without having to uncompress each log file.
Use the below syntax to search through a compressed file for a specific pattern. In the example below we search for “Error” in the production.log.gz file.
Search for Patterns in Files Using gunzip:
- [root@dev archive]# gunzip -c production.log.gz | grep -i Error | more
There are numerous things happening in the example noted above. First we use the gunzip command with the -c switch to print the output of the production.log.gz file to standard output which will be the shell you are connected to the server with or the monitor that is attached to the server. Next we pipe the output printed to the screen or shell to the grep command to filter the output results for the word “error”. The -i switch for grep specifies to not worry about the case of the word we are filtering for so Error, ERROR, and error would all be words we filter for. Last but not least because the output could include thousands of lines depending on how big the log file is we pipe the final results to the more command which will limit the amount of lines output to the screen. After viewing the initial screen of results you can type the space bar to move to the next screen of results.
Please note that using gzip instead of gunzip in the command above will output gibberish to the screen and if you prefer using the gzip command instead you will need to use the -d switch as well to decompress the file first as shown in the example below.
Search For Patterns in Files Using gzip:
- [root@idev archive]# gzip -d -c production.log.gz | grep -i Error | more
The difference again is you must specify to gzip to decompress the file with the -d switch but you are not required to do so with gunzip.