Tuesday, March 8, 2016

Selecting columns from files | Linux command "cut"



CUT, Selecting columns from files
In my previous post I have covered the grep command on a high level basis. Grep is often used to search for data in a file or multiple files at once. Perhaps the files you are searching are column based. Web server logs for instance. Using the cut command would allow you to effectively select characters, columns and ranges of them. As with other commands I write about I am not going into great detail. Some more options are available for this command but these are the ones I use the most. A full manual can be found here.

Cut can be used to do a variety of things. Displaying ranges of characters or displaying columns or fields if you like.

Lets take the following contents of the file fruit.txt for example.
apple green tree
banana yellow tree
strawberry red plant

If you would want to display the second character of each line in this file you would use the "-c" operator appended with the character number. "-c2" for the second character of each line for example.
cut -c2 fruit.txt
p
a
t

You can also use -c1-3 to display characters 1 through to 3.
cut -c1-3 fruit.txt
app
ban
str

If you would want to display the second column or field you would use the "-f" operator to select the field number. The "-d" operator will allow you to specify a single delimiter like a space of comma between the single quotes.
cut -d' ' -f2 fruit.txt
green
yellow
red

Also with the "-f " you can specify a range or the column numbers. Like this for a range.
cut -d' ' -f2-3 fruit.txt
green tree
yellow tree
red plant

And this for the column numbers.
cut -d' ' -f1,3 fruit.txt
apple tree
banana tree
strawberry plant

1 comment:

How to create a software RAID array in Linux | mdadm

In my previous post I explained on the most common used RAID levels and their write penalties. In this post I will show how you c...