How to use zcat to concatenate compressed and plain text files

The zcat command is an analogue of cat, which displays the contents of one or more files. More specifically, the cat command is designed to merge several text files. The command runs like this:

cat file1 file2 file3

The contents of all files will be consistently output to standard output.

If you specify only one file:

cat file1

then its contents will be displayed. Quite often, the cat command is used for this purpose.

The zcat command works roughly the same, it only displays the contents of archive files with the .gz extension.

At one time you can display the contents of one or more files, for example

zcat access_log.1.gz access_log.2.gz access_log.3.gz

You can use wildcard characters to display text from all the files in the current folder at once:

zcat access_log.*gz

How to simultaneously display the contents of text files and archives?

For example, you need to concatenate a text file and a compressed file if you try to execute a command like this:

zcat access_log access_log.1.gz

Then it will actually show the .gz file, but for the access_log file (plain text file), an error message will be displayed:

gzip: access_log: not in gzip format

And the file will not be shown.

To simultaneously display the contents of both text and archive files, you can use the construction of zcat and cat commands. Example:

zcat access_log.*gz | cat access_log -

As a result, the first command (zcat access_log.*gz) will read the contents of all the .gz files and pipe (|) to the next command. That is, for the next command it will be the standard input. Then the second command (cat access_log -) reads the contents of the first access_log file, then the contents of the second file, which is specified by – (hyphen), which means standard input. In this case, using standard pipe input, the zcat command send the contents of the access_log.*gz files. It turns out that at the very beginning the contents of the access_log file will be shown, and then what the zcat command read, that is, all the access_log.*gz. files.

So, using these two commands, you can simultaneously read and merge compressed files and files in plain text.

If we want the output of the zcat command to be shown first, then swap the files as cat options, that is, instead of access_log -, write – access_log (hyphen is placed to be the first, that is, it first reads from standard input and then reads real files):

zcat access_log.*gz | cat - access_log

How to add a string to cat/zcat output

By the way, the same method can be used to add text lines to the output file, for example, before displaying or after the contents of files. For example:

echo "Web logs" | cat - access_log

Recommended for you:

Leave a Reply

Your email address will not be published.

Looking for a job in IT. Details: https://miloserdov.org/?p=2900