cut

The cut utility is a great example of the UNIX philosophy of "do one thing, and do it well." cut just cuts lines of text, based on a (single-character) delimiter.

There are two basic forms in which cut is generally used:

1. Grab These Columns (cut -c)

One form of cut gets certain characters, or columns of characters, out of a file. This is done with the cut -c command. So we can get the 5th character of the string:

$ echo "Hello, World" | cut -c 5
o

Or we can get the first 5 characters:

$ echo "Hello, World" | cut -c -5
Hello

Or from character #5 onwards:

$ echo "Hello, World" | cut -c 5-
o, World

Or even just characters 2-5:

$ echo "Hello, World" | cut -c 2-5
ello

Or maybe just select characters 5, 8 and 9:

$ echo "Hello, World" | cut -c 5,8,9
owo

2. Delimited (cut -d)

The other method is to use a delimiter. For example, the /etc/passwd file looks something like thism with the fields delimited by the ":" (colon) symbol:

root:x:0:0:root:/root:/bin/bash
steve:x:1000:1000:Steve Parker,,,:/home/steve:/bin/bash

In this example, field 1 is "root" (or "steve"), field 2 is "x", and so on.... the last field (7) is "/bin/bash" for both accounts, in this case.

So we just have to specify the delimiter (:) and the field number(s). Field 1 is the account name, 6 is the home directory, field 3 is the UserID...

$ cut -d: -f1 /etc/passwd
root
steve
$ cut -d: -f6 /etc/passwd
/root
/home/steve
$ grep "^root:" /etc/passwd | cut -d: -f3
0

(In the last example, we got *just* the root account, with a grep which searches for a line starting with "root:", which could only be the root account, and not (for example) "Fred Troot" which would also match a search for "root")

cut is one of those really simple, but really useful utilities. And because it's very simple, it's nice and quick (which matters a lot if you're looping through a few hundred times.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: