Data Streams and the UNIX Shell
(Page 1 of 4 )
You can consider most of the things happening around you to be a stream of data. Your girlfriend loves you; two cars crash in a corner; your mother calls you to wish you a happy birthday; etc. Everything is just a stream of data that your brain takes and processes. The quality of your life very much depends on how your brain interprets this stream, however this on its own depends on what streams arrive there. In UNIX, things are very much the same. The tools just interpret and filter the data. Nevertheless, how these streams get from one place to another can very much influence the result.
Today I will continue my series on Shell programming and cover how we stream the data from one tool to another, from a tool to a file, and what additional options we have. For this I will not cover some facts that you should already know, like how to use the Shell terminal, how commands work inside the shell, and so forth. For this information, please go back and read my earlier articles. If you are ready for this one, let's begin.
First, we can redirect the standard input and standard output of the file. For this, the shell uses a couple of syntactical symbols. If you want to redirect the standard input, you can use the <symbol. After this, just add the file which you want to direct as input. In order to show you how this works, I will use certain functions throughout this article, explained in the paragraph below.
The cat is what prints the content of a file to the standard output. The head is what prints the first n lines to the standard output. Then there is the tail which does the same, but it uses the last n lines. I will also use the sort to sort the lines of the input and print them to the standard output. By default, every tool/filter will use the standard input as input if you do not specify an exact file.
How can we sort the lines of a file? Just like this:
sort < alfa.txt
To redirect the standard output, we will use a similar syntax, but in the opposite direction with the >character.
cat alfa.txt > content_of_alfa.txt
It is good to remark that the > will delete a file that already exists if it has the same name; it will then create a new file into which it will place the output of the command. If you want to simply append the output of a command to a file, you can use the >>syntax instead of the >.
You can use these together. Therefore, for instance, if you want to sort the contents of a file and print the result to a file, you can proceed as follows:
sort < alfa.txt > sorted_alfa.txt
Next: Pipes >>
More Miscellaneous Articles
More By Gabor Bernat