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. To sort a file & output it to another fileType 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. To save a directory listing as a fileType 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). Figure 49. This example shows how the 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.To append output to an existing fileType 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 50. This example uses >> to append another directory to the one in Figure 49 and display the combined files with the cat command.To create a text file with cat
Tip
To combine files with catType 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. |