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

and an equivalent awk command:

$ awk -F'#' '{print $2}' < ipaddr.list

You can even use cut to handle non-matching delimiters by using more than one cut. You may be better off using a regular expression with awk for this, but sometimes a couple of quick and dirty cuts are faster to figure out and type.

Here is how you can get the field out from between square brackets. Note that the first cut uses a delimiter of open square bracket (-d'[') and field 2 (-f2 starting at 1). Because the first cut has already removed part of the line, the second cut uses a delimiter of closed square bracket (-d']') and field 1 (-f1).

$ cat delimited_data
Line [l1].
Line [l2].
Line [l3].

$ cut -d'[' -f2 delimited_data | cut -d']' -f1
l1
l2
l3

See Also

  • man cut

  • man awk

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.38.176