Pipes and Filters
Notes:
-
Pipes. A pipe takes the output from one command and uses it as input to the
next command. Example:
-
ls -l /etc | more
display a long listing of the /etc directory and pipe the output through
the more command so that it is displayed one screen at a time.
-
Remember:
-
to send the output of a command to a file, use redirection
-
to send the output of a command to another command, use piping
-
Commands that are used in pipelines to modify the output from other commands
are being used as filters. All of these commands can be used on their own
as well. Commands that are frequently used in pipelines include: grep, sort,
wc
-
wc: Count bytes, words and lines
-
wc /etc/passwd
Count the number of bytes, words and lines in /etc/passwd
-
wc -l /etc/passwd
Count the number of lines in /etc/passwd
-
wc -w /etc/login.defs
Count the number of words in /etc/passwd
-
sort: sort lines in a file
-
sort /etc/group
Sort the contents of /etc/group
-
sort -r /etc/group
Sort the contents of /etc/group in reverse order
-
ls -l | sort -k5n
Sort the output of ls -l on the size of the files. k5 specifies sort starting
on field 5 and n selects a sort in numerical order
-
More examples:
-
What command will count the number of files in the directory
var/spool/mail?
Answer: ls /var/spool/mail | wc -w
-
What command will count the number of users whose login shell is /bin/bash?
(Recall that the login shell is the last entry in the line for each user
in the file /etc/passwd)
Answer: grep /bin/bash$ /etc/passwd | wc -l
-
What command will display a list of everyone who is logged on sorted by their
usernames?
Answer: who | sort
Exercises:
-
Copy the file /etc/services to your own home directory. This file contains
a list of the port numbers used for Internet network services.
-
How many lines are in the file.
-
Display all of the lines for tcp services.
Count the number of lines for tcp services.
-
Display all of the lines for udp services.
Count the number of lines for udp services.
-
Use the "last" command to display the record of all login sessions.
What command counts the number of login sessions for floopy?
-
Display a long directory listing for the /etc directory.
Pipe the output of the long directory listing through a grep command that
will only display the entries for directories in /etc.
Questions & Answers:
The file called "commands" contains:
cal /usr/bin 9416
date /bin 2860
who /usr/bin 8692
cat /bin 18056
lpd /usr/sbin 42012
-
What is the output of the pipeline:
sort -r commands | head -1
Answer: who /usr/bin
8692
-
What is the output of the pipeline:
sort -bk3n commands | head -1
Answer: date /bin
2860
-
What is the output of the pipeline:
grep ^c commands | wc -l
Answer: 2
-
What is the output of the pipeline:
grep usr commands | wc -l
Answer: 3
-
What is the output of the pipeline:
grep at commands | sort | head
-1
Answer: cat /bin
18056
Copyright ©
L.M.MacEwan