May 6, 2008

Cat examples


1. To display the file notes, enter:
cat notes

If the file is longer than one screenful, it scrolls by too quickly to
read. To display a file one page at a time, use the more command.

2. To concatenate several files, enter:
cat section1.1 section1.2 section1.3 > section1

This creates a file named section1 that is a copy of section1.1 fol-
lowed by section1.2 and section1.3.

3. To suppress error messages about files that do not exist, enter:
cat -s section2.1 section2.2 section2.3 > section2

If section2.1 does not exist, this command concatenates section2.2 and
section2.3. Note that the message goes to standard error, so it does
not appear in the output file. The result is the same if you do not
use the -s option, except that cat displays the error message:
cat: cannot open section2.1

You may want to suppress this message with the -s option when you use
the cat command in shell procedures.

4. To append one file to the end of another, enter:
cat section1.4 >> section1

The >> in this command specifies that a copy of section1.4 be added to
the end of section1. If you want to replace the file, use a single >

5. To add text to the end of a file, enter:
cat >> notes
Get milk on the way home

Get milk on the way home is added to the end of notes. With this syn-
tax, the cat command does not display a prompt; it waits for you to
enter text. Press the End-of-File key sequence ( above) to
indicate you are finished.

6. To concatenate several files with text entered from the keyboard,
cat section3.1 - section3.3 > section3

This concatenates section3.1, text from the keyboard, and section3.3
to create the file section3.

7. To concatenate several files with output from another command, enter:
ls | cat section4.1 - > section4

This copies section4.1, and then the output of the ls command to the
file section4.

8. To get two pieces of input from the terminal (when standard input is a
terminal) with a single command invocation, enter:
cat start - middle - end > file1

If standard input is a regular file, however, the preceding command is
equivalent to the following:
cat start - middle /dev/null end > file1

This is because the entire contents of the file would be consumed by
cat the first time it saw - (dash) as a file argument. An End-of-File
condition would then be detected immediately when - (dash) appeared
the second time.

No comments: