In all of the Unix commands up to this point that produced outputsuch as man and lsthe command output appears in the Terminal window. This is called the
standard output device of Unix.
But the shell can also redirect the output of a command to a file instead of to the screen. This
output redirection enables you to create files by writing command output to a file.
Output redirection uses the greater-than character (>) to tell the shell to place the output of a command into a file rather than listing it to the screen. If the output file already exists, it is overwritten with the new information.
Similarly, a pair of greater-than signs (>>) tells the shell to append the output of a command to the end of a file rather than erasing the file and starting from the beginning. If the output file does not already exist, the shell creates a new file with the name you specified.
This section offers some examples of output redirection.
Type sort
file >
output-file and press
For example, sort sample.txt > alpha.txt would sort the lines in the file named
sample.txt and write them to a file named
alpha.txt .
Type ls >
output-file and press
For example, ls -la > list.txt creates a file named
list.txt that contains a complete directory listing in the long format (Figure 49 ).
ls command can be used to save a directory listing as a text file. The
cat command was used in the illustration to display the contents of the new file.
Type
command >>
output-file and press
For example, ls -la Documents >> list.txt would append a directory listing for the Documents subdirectory to the list.txt file (Figure 50 ).
Figure 49 and display the combined files with the
cat command.
1. | Type cat > output-file (for example, cat > test.txt) and press Figure 51. Using thecat command with an output file name starts cat and waits for text entry. |
2. | Enter the text you want to include in the file. You can press Figure 52. Enter the text you want to include in the file. |
3. | When you're finished entering text, press Figure 53. Press
|
Normally, the cat command uses a source-file argument; that is, you normally tell cat to list a specific file to the screen. If you do not specify a source-file for cat, it takes source data from the
standard input device , which is usually the keyboard, and redirects it to the output-file.
Type cat
file1 ... >
output-file and press
For example, cat firstfile.txt secondfile.txt thirdfile.txt > combinedfile.txt combines the files named
firstfile.txt, secondfile.txt , and
thirdfile.txt , in that order, and saves them as a file named
combinedfile.txt .