Selecting Columns – cutJune 16, 2006
The cut command takes a vertical slice of a file, printing only the specified columns or fields. Like the sort command, the cut command defines a field as a word set off by blanks, unless you specify your own delimiter. It's easiest to think of a column as just the nth character on each line. In other words, "column 5" consists of the fifth character of each line.
Consider a slight variation on the company.data file we've been playing with in this section:
cut -c1-6 company.data
If you want to print just columns 4 and 8 of each line (the first letter of the department and the fourth digit of the serial number), use the -c4,8 flag, as in this command:
cut -c4,8 company.data
And since this file obviously has fields delimited by colons, we can pick out just the last names by specifying the -d: and -f3 flags, like this:
cut -d: -f4,3 company.data
Here is a summary of the most common flags for the cut command:
-c [n | n,m | n-m] Specify a single column, multiple columns (separated by a comma), or range of columns (separated by a dash).
-f [n | n,m | n-m] Specify a single field, multiple fields (separated by a comma), or range of fields (separated by a dash).
-dc Specify the field delimiter.
-s Suppress (don't print) lines not containing the delimiter.