Using Redirection
In addition to supporting pipes, Ubuntu allows you to redirect
output using the >
and <
symbols. Using the first, you can, for
example, send the output from a program directly to a file, whereas the
second accepts input from a program.
Redirecting Output
The following command creates a file called files.txt in your home folder containing the
output from ls -al
:
ls -al > ~/files.txt
If files.txt already exists, it will be overwritten; otherwise, it will be created.
When you issue that command, you wonât see anything on the screen, because the output that would have been displayed has been redirected to a file. But you can verify that the command worked by entering the following, which displays the fileâs contents:
cat ~/files.txt
The result of issuing this command will look something like Figure 7-15.
Figure 7-15. The result of displaying files.txt
But what if you want to know which files and folders were created first? The answer would be to sort them by column 6, and you could use this command to do it:
ls -al | sort -k6 > ~/files.txt
Redirecting Input
If you need to keep the file sorted alphabetically but still wish to sometimes view the lines in date order, you can issue the following command on it instead:
sort -k6 < ~/files.txt
This opens up files.txt,
reads it in, and passes its contents to the command immediately
preceding the <
symbol.
You could even extend that ...
Get Ubuntu: Up and Running now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.