When running a command, output is typically printed to your terminal.
This is referred to as standard output (and is technically a file). But what if we want to…
Recall that cat can be used to print the contents of a file. Suppose we have the following text in world.txt:
Running cat world.txt gives:
To redirect output to some file named FILE, follow the command producing the output with > FILE or >> FILE.
> overwrites the contents of the existing file.>> appends to the contents of the existing file (i.e, it starts at the end).FILE if it doesn’t already exist.Now we append the contents to the end of world_copy.txt:
What does world_copy.txt contain now?
The echo command simply prints its input. What does file.txt contain after running these commands?1
By flipping the > operator, we can redirect the contents of a file to a program. That is, for some COMMAND and FILE, we write:
COMMAND < FILE
Well what if we want to save this output into another file1? We can use both!
In some cases, you’d like to take the output of one program and pass it directly to another program (without an intermediate file).
For this, we have the pipe operator (|)1:
COMMAND1 | COMMAND2
It passes the output of the left-hand program (COMMAND1) to the input of the right-hand program (COMMAND2).
sort to uniqThe command uniq outputs all of the unique lines in a file.
But there’s a problem. It only compares neighboring lines!
Let’s try uniq on numbers.txt…
What’s the solution?
sort to uniqWe sort first! We can do this with a pipe.
>/>> and |? Why not!Note that you can combine these operators. For example:
These are the commands to become familiar with today:
sortuniqcutpastegrepInstead of me tediously explaining each one, let’s look at some MAN pages together to learn how to read them1.
Recall that to pull up the MAN (manual) pages, we run the following in the terminal,
replacing command with the name of your desired program.