Cat

The cat command is so called because (in the words of its man page) it "concatenates files and prints them to standard output." So the command cat /etc/passwd simply prints the content of the file /etc/passwd to the screen.

If you cat a number of files, you will see them printed to the screen in the order they are named:

cat filel file2 file3

So far, this is not very useful, but you can now redirect the output to a new file:

cat filel file2 file3 > bigfile

You now have a combined file bigfile containing the contents of the three original files.

Numbering lines in a file

The cat command has the sometimes-useful capability of being able to number the lines in a file. This is done with the -n option. So if you have a file fruits:

[email protected]:~> cat fruits apple banana cherry [email protected]:~> cat -n fruits

1 apple

2 banana

3 cherry

The -b option numbers only non-blank lines. It quite often happens that for some reason you have a file that contains hundreds of blank lines as well as some information you actually want: You could simply use cat -b and direct the output to a new file.

Replacing blank lines and tabs

Another useful options is -s, which replaces any number of blank lines with a single blank line (removing unwanted white space from the file, while keeping the structure).

So, for example:

[email protected]:~> cat gapfruits apple orange peach pear [email protected]: apple cat -s gapfruits orange peach pear

The -T replaces tabs with visible characters (AI):

[email protected]:~> cat morefruits kiwi mango pear quince [email protected]:~> cat -T morefruits kiwiAImango pear quince

So there was a tab on the first line and spaces on the second. Sometimes the distinction between tabs and spaces really matters: makefiles and tab-separated files for instance. The -T option enables you to tell the difference easily.

Making sense of binary files

If you use cat on a binary file that contains nonprintable characters (for example, an executable file or a file created by an application such as Microsoft Word), you will typically see a lot of "garbage" on the screen, and in some cases your terminal will be messed up so that the characters before the prompt display incorrectly. The -v option to cat avoids the garbage by displaying nonprinting characters more intelligibly. So cat -v wordfile.doc is a better way of peeping inside such a file than plain cat. See also the sections in this chapter on the commands strings and antiword.

If your terminal settings get messed up so that your prompt is made up of weird characters, you can usually remedy the situation by typing the command reset. As you type it, you may see the wrong characters appearing on the screen, but as soon as you press Return, the terminal should be back to normal. This applies whether you are using a text console, an xterm, or a KDE konsole window.

Was this article helpful?

0 0

Post a comment