100 Useful Command-Line Utilities

by Oliver; 2014

7. cat, zcat, tac

cat prints the contents of files passed to it as arguments. For example:
$ cat file.txt
prints the contents of file.txt. Entering:
$ cat file.txt file2.txt
would print out the contents of both file.txt and file2.txt concatenated together, which is where this command gets its slightly confusing name. Print file with line numbers:
$ cat -n file.txt      # print file with line numbers
cat is frequently seen in unix pipelines. For instance:
$ cat file.txt | wc -l		# count the number of lines in a file
$ cat file.txt | cut -f1	# cut the first column
Some people deride this as unnecessarily verbose, but I'm so used to piping anything and everything that I embrace it. Another common construction is:
cat file.txt | awk ...
We'll discuss awk below, but the key point about it is that it works line by line. So awk will process what cat pipes out in a linewise fashion.

If you route something to cat via a pipe, it just passes through:
$ echo "hello kitty" | cat
hello kitty
The -vet flag allows us to "see" special characters, like tab, newline, and carriage return:
$  echo -e "\t" | cat -vet
^I$
$ echo -e "\n" | cat -vet
$
$
$ echo -e "\r" | cat -vet
^M$
This can come into play if you're looking at a file produced on a PC, which uses the horrid \r at the end of a line as opposed to the nice unix newline, \n. You can do a similar thing with the command od, as we'll see below .

There are two variations on cat, which occasionally come in handy. zcat allows you to cat zipped files:
$ zcat file.txt.gz
You can also see a file in reverse order, bottom first, with tac (tac is cat spelled backwards).

<PREV   NEXT>