Field splitting

Suppose we wanted to print only the last name of each of our computer scientists. We could use the read command's built-in word splitting to do this, by specifying two variables after -r:

while read -r firstname lastname ; do
    printf '%s\n' "$lastname"
done < fcs

This yields the names we wanted:

Thompson
Ritchie
McCarthy
Wall

Because there is more than one variable name given, each line read is split at the first space or tab, and the line up to that point is saved into the firstname variable. Because lastname is the last variable on the line, the entire rest of the line—not only the last field—is saved into that.

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.