my ideas in action

print some columns from CSV file

If you have a CSV ( comma separated values file) and you need to print only some columns then you can use sed, awk or cut. Today I will show the “cut” command. Do not confuse it with “cat” !!

CUT is quite easy to use and is more simple than AWK or SED. For example if you have a file like this

$ cat datafile.csv

device1 device2 device2a device4b device5a device8 device9

1 56 8 99 5 41 36 8

22 5 99 89 56 56 2

1 0 2 5 9 63 5

As you can see the delimiter is not comma but space. If you want to print only columns 2,3 and 5 then “cut” is the best tool.

$ cut -d” ”  -f2,3,5 datafile.csv

device2 device2a device5a

56 8 5

5 99  56

0 2 9

-d” ” = means to use ” ” (space) as delimiter in the input file

-f2,3,5 = means to print only the fields 2, 3 and 5

So by default the output delimiter is space. If you want a specific delimiter, like tab, you can use this :

$ cut -d” ”  -f2,3,5 –output-delimiter=$’\t’  datafile.csv

device2         device2a        device5a

56                 8                       5

5                   99                     56

0                  2                        9

The syntax $’\t’ is special because cut do not accept TAB as “\t”

For another delimiter you can use the option like : –output-delimiter=”.:.”

$ cut -d” ”  -f2,3,5 –output-delimiter=$’\t’  datafile.csv





Of course for all this there is a AWK or SED command but I think that for simple column selection a CUT command is easier.

More than that. The CUT command give also the possibility to select only some bytes or characters from the file. For example to print only the characters from 2 to 5 you have to use :

$ cut -c2-5 datafile.csv



2 5


not very useful in my case but nice to have in case the input file format do not have a delimiter.

see more info with “man cut”


Leave a Reply

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

You are commenting using your 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

%d bloggers like this: