UNIX Tutorial Three
UNIX Tutorial Three
We have already seen one use of the cat command to write the contents of a file to the screen.
% cat
Then type a few words on the keyboard and press the [Return] key.
Finally hold the [Ctrl] key down and press [d] (written as ^D for short) to end the input.
If you run the cat command without specifing a file to read, it reads the standard input (the keyboard), and on receiving
the 'end of file' (^D), copies it to the standard output (the screen).
In UNIX, we can redirect both the input and the output of commands.
Then type in the names of some fruit. Press [Return] after each one.
pear
banana
apple
^D {this means press [Ctrl] and [d] to stop}
What happens is the cat command reads the standard input (the keyboard) and the > redirects the output, which
normally goes to the screen, into a file called list1
% cat list1
Exercise 3a
Using the above method, create another file called list2 containing the following fruit: orange, plum, mango, grapefruit.
Read the contents of list2
1 of 4 03/04/20, 2:27 am
UNIX Tutorial Three http://www.ee.surrey.ac.uk/Teaching/Unix/unix3...
The form >> appends standard output to a file. So to add more items to the file list1, type
peach
grape
orange
^D (Control D to stop)
% cat list1
You should now have two files. One contains six fruit, the other contains four fruit.
We will now use the cat command to join (concatenate) list1 and list2 into a new file called biglist. Type
What this is doing is reading the contents of list1 and list2 in turn, then outputing the text to the file biglist
% cat biglist
% sort
Then type in the names of some animals. Press [Return] after each one.
dog
cat
bird
ape
^D (control d to stop)
ape
bird
cat
dog
Using < you can redirect the input to come from a file rather than the keyboard. For example, to sort the list of fruit, type
2 of 4 03/04/20, 2:27 am
UNIX Tutorial Three http://www.ee.surrey.ac.uk/Teaching/Unix/unix3...
3.4 Pipes
To see who is on the system with you, type
% who
This is a bit slow and you have to remember to remove the temporary file called names when you have finished. What
you really want to do is connect the output of the who command directly to the input of the sort command. This is
exactly what pipes do. The symbol for a pipe is the vertical bar |
% who | sort
will give the same result as above, but quicker and cleaner.
% who | wc -l
Exercise 3b
Using pipes, display all lines of list1 and list2 containing the letter 'p', and sort the result.
Summary
Command Meaning
cat file1 file2 > file0 concatenate file1 and file2 to file0
3 of 4 03/04/20, 2:27 am
UNIX Tutorial Three http://www.ee.surrey.ac.uk/Teaching/Unix/unix3...
4 of 4 03/04/20, 2:27 am