Cat

From LQWiki
Jump to: navigation, search

Cat is ostensibly a tool used for concatenating (that is, chaining together) a number of files to standard output, but in practice it is often used to display the contents of one file to standard output (effectively catenating one file), or using it to create small files or use the terminal as a scratch pad (by using shell redirection).

Examples

Say we have two files, file1 and file2. If we wanted to just display the two files to standard output, we could use

cat file1 file2

which we can then use to quickly display the contents of one or many files on standard output.

If we want to create another file file3 which has the contents of file1 and then the contents of file2, we could use

cat file1 file2 > file3

which makes use of shell redirection. The cat program displays the contents of file1 then file2 to standard output, and the > tells the shell to run the program with the standard output in the contents of file3.

We can use shell redirection capabilities to have cat act as a bare-bones text editor. cat, without any arguments, simply echoes lines typed from standard input to standard output. If we redirect the standard output to a file, we get lines we type in sent to that file. For example, if we wanted to create a dotfile quickly, say, we could simply use cat as follows

cat > .somefile

and then type in the contents, using Control-D to finish (Unix and Unix-like systems will stop accepting input when it recieves Control-D). Of course, this is impractical to use to write large files since we can only edit line by line and cannot edit previously entered lines.

If we merely want to type ourself a quick note to throw away (eg, have it resident in a terminal window), without using some Post-it note like tool, we can use cat to redirect to the null device, /dev/null, which effectively throws away lines we edit (but still keeps the lines we entered on the screen), as follows:

cat > /dev/null

In a script you can use cat to put data into a file like this:

cat > fillme << EOF
this is the first line
this is the last line
EOF

As always, you can use the > operator to rewrite a file and the >> operator to append to a file:

cat >> file

appends your input at the end of file

Provided by

Most (all?) Linux distributions incorporate this from the GNU Coreutils: and use its man page


Related Commands

These all relate to the output or processing of entire files

  • tac -- line-reversed cat
  • nl -- output with line numbers
  • od -- dump in octal and other character representations.
  • rev -- character-reversed cat
  • base32 -- Encode in printable characters
  • base64 -- Encode in printable characters.