Cut

From LQWiki
Jump to: navigation, search

cut

The cut command is a handy program for extracting pieces of a line of text. The most useful options are "-d" and "-f", which are for setting the "delimiter" character that separates items, and for telling Cut which "fields" you want it to print.

For example, let's say you have the following line of text, and you only want the 3rd and 6th columns:

foo,bar,baz,stuff,blah,oogabooga

you could run it through this cut command:

cut -d',' -f 3,6

and the output would be:

baz,oogabooga

A more practical example

Perhaps you want to take the output of ls -l but only see the permissions, size, and name of the files.
Here is some sample output of ls -l:

-rw-r--r--    1 pete     users        65767 Mar  5 17:36 school.pdf
-rw-------    1 pete     users        34552 Mar  5 17:36 soup.jpg
-rw-rw-r--    1 pete     users           63 Mar  5 17:36 taxes.txt

First, here's a trick to use tr to squeeze multiple spaces into just one space:

$ ls -l | tr -s ' ' 
-rw-r--r-- 1 pete users 65767 Mar 5 17:36 school.pdf
-rw------- 1 pete users 34552 Mar 5 17:36 soup.jpg
-rw-rw-r-- 1 pete users 63 Mar 5 17:36 taxes.txt


And now, here's how to use cut to chop it into bits based on the spaces as a delimiter:

$ ls -l | tr -s ' ' | cut -d' ' -f 1,5,9
-rw-r--r-- 65767 school.pdf
-rw------- 34552 soup.jpg
-rw-rw-r-- 63 taxes.txt

See Also

paste, join