<tt>cut</tt>, <tt>awk</tt>: Cut Selected Fields



next up previous contents
Next: Exercises Up: Tips Using Shell Previous: stty -echo: Passwords

cut, awk: Cut Selected Fields

cut and awk may both be used to select a specific field from the output of a command. A typical application would be to create a list of currently logged-in users:

#!/bin/sh
#
# using cut:
USERS=`who | cut -f1 -d" "`
echo "Users on the system are: $USERS."

# using awk:
USERS=`who | awk '{print $1}'`
echo "Users on the system are: $USERS."

In the first example, cut takes its input from the who command. -f1 specifies that the first field is to be cut out from each line, and -d" " specifies that the field delimiter is a space.

In the second example, awk takes its input the same way cut did, then prints the first field (space is the default field delimiter for awk).

In general, cut is a much simpler command to use. awk is a full language: scripts can be written using awk as the language instead of the shell script.



Super-User
Fri Feb 17 15:55:40 EST 1995