cut

Shell (~bash)

Recently, when proofreading my xargs post, a coworker asked “Cut? What does that do?” So, back into the trenches to investigate one of the super-cool, fundamental building blocks of really great command line concoctions.

% echo "1,red,grumpy\n2,orange,sleepy\n3,yellow,doc"
1,red,grumpy
2,orange,sleepy
3,yellow,doc

% echo "1,red,grumpy\n2,orange,sleepy\n3,yellow,doc" | cut -d, -f2
red
orange
yellow

According to the man page, cut “cuts out selected portions of each line of a file”. As usual, instead of an input file, we can use the output of some other command piped in through stdin. the -d, option above tells cut that the lines to be processed are comma-delimited. The -f2 specifies that we want the second “field” in each line returned.

To conserve some typing, let’s set up a file to experiment on:

% echo "1,red,grumpy,monday\n2,orange,sleepy,tuesday\n3,yellow,doc,wednesday" \
>> test.txt

Now, we can use cut on the file rather than stdin:

% cut -d, -f2 test.txt
red
orange
yellow

We can also do multiple fields in several ways:

% cut -d, -f2,4 test.txt
red,monday
orange,tuesday
yellow,wednesday

% cut -d, -f2-4 test.txt
red,grumpy,monday
orange,sleepy,tuesday
yellow,doc,wednesday

% cut -d, -f2- test.txt
red,grumpy,monday
orange,sleepy,tuesday
yellow,doc,wednesday

% cut -d, -f-3 test.txt
1,red,grumpy
2,orange,sleepy
3,yellow,doc

One important caveat…cut won’t reorder fields:

% cut -d, -f2,4 test.txt
red,monday
orange,tuesday
yellow,wednesday

% cut -d, -f4,2 test.txt
red,monday
orange,tuesday
yellow,wednesday

Reordering fields takes something a little more sophisticated; like awk or a while loop. (More on awk and while later.)

cut will, however, happily work on bytes or characters rather than delimited fields if you have data that’s already columnar. Look at the output of ps, for example:

% ps x
PID   TT  STAT      TIME COMMAND
251   ??  Ss     0:00.95 /sbin/launchd
254   ??  S      0:01.30 /usr/libexec/UserEventAgent -l Aqua
256   ??  S      0:06.10 /usr/sbin/distnoted agent
259   ??  S      0:02.46 /System/Library/Frameworks/ApplicationServices.frame
261   ??  S      0:00.01 /usr/sbin/pboard

cut can condense and pick out just the pieces you want to see:

% ps x | cut -c-6,18-40 
PID      TIME COMMAND
251   0:00.97 /sbin/launchd
254   0:01.30 /usr/libexec/
256   0:06.13 /usr/sbin/dis
259   0:02.47 /System/Libra
261   0:00.01 /usr/sbin/pbo

So, go experiment with cut. It does one pretty straightfoward thing…and it does it really well.

Published: June 29 2012

Author: trimble