Lesson 22: Combining commands¶
One of the most powerful features of Linux is that you can send the
output from one command or program to any other command (as long as the
other command accepts input of some sort). We do this by using a
pipe character, represented
as: |
. The chain of commands is commonly known as a pipeline.
[learner planets]$ grep surface earth.txt | wc
1 9 50
The lines within 'earth.txt' that contain the word 'surface' (filtered
by grep
) are passed into the pipeline to the word count
(wc) program to display the
line, word and byte counts of the input parameter (retrieved from the
pipeline).
Sorting Numerical Lists¶
Firstly, let's create the directory ~/learning_linux/number
and
change to the 'number' directory. Now copy the file
/opt/guided/numbers.txt file to the current directory.
Try running the sort command on the 'numbers.txt' file - is the output what you expect?
[learner number]$ sort numbers.txt
Without any switches, sort
arranges the input by digit, then
alphabetically, hence why 112 is listed before 14 (the second digit in
112 is smaller than the second digit in 14). Try running the sort
command again with the -n
switch. Use the manual page to discover what
that switch does.
To display unique entries in 'numbers.txt', pipe the output of the
previous command into uniq. Please
note that for uniq
to work, the file contents must first be sorted
because adjacent identical lines are collapsed into one. Running uniq
before sort -n
will yield unwanted results!
Note
Whenever chaining many piped commands together, test each step as you build it!