Cutting Out Parts of Your Output

Problem

You need to look at only part of your fixed-width or column-based data. You’d like to take a subset of it, based on the column position.

Solution

Use the cut command with the -c option to take particular columns: Note that our example 'ps' command only works with certain systems; e.g., CentOS-4, Fedora Core 5, and Ubuntu work, but Red Hat 8, NetBSD, Solaris, and Mac OS X all garble the output due to using different columns:

$ ps -l | cut -c12-15
PID
5391
7285
7286
$

or:

$ ps -elf | cut -c58-
(output not shown)

Discussion

With the cut command we specify what portion of the lines we want to keep. In the first example, we are keeping columns 12 (starting at column one) through 15, inclusive. In the second case, we specify starting at column 58 but don’t specify the end of the range so that cut will take from column 58 on through the end of the line.

Most of the data manipulation we’ve looked at has been based on fields, relative positions separated by characters called delimiters. The cut command can do that too, but it is one of the few utilities that you’ll use with bash that can also easily deal with fixed-width, columnar data (via the -c option).

Using cut to print out fields rather than columns is possible, though more limited than other choices such as awk. The default delimiter between fields is the Tab character, but you can specify a different delimiter with the -d option. Here is an example of a cut command using fields:

$ cut -d'#' -f2 < ipaddr.list ...

Get bash Cookbook 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.