8.4 Zipping from STDOUT

You can combine the cat, zcat and gzip commands to optimize efficiency in your bash scripts. In the example below for instance, you can ‘display’ the content of a file using cat and then directly zip it using gzip and store the zipped file in ‘test.gz’:

$ cat test.txt | gzip > test.gz

Of course you can also go the other way around, start with a zipped file, and look at a specific line of that file by combining the zcat and the head command. Like this, you never actually have to unzip the file.

$ zcat test.gz | head -n1
Line 1

You can of course add as many intermediate steps as you wish:

$ zcat test.gz | sed 's/Zipping/Pipeing/' | gzip > new.gz
$ zcat new.gz | tail -n2
Pipeing is great!
Pipeing is great!

Note: We will learn more about sed later…