Monday, April 14, 2008

UNIX: "cut" Can't Cut It

What I wanted to use was:
cut 3,4,1
However, I discovered the hard way that cut can't be used to reorder fields. It treats the above the same as if I had typed:
cut 1,3,4
Well, awk to the rescue!
awk -F '\t' '{ printf "%s\t%s\t%s\n", $3, $4, $1 }'

3 comments:

Dave said...

You can get the same effect using a combination of cut and paste:

$ cat tmp
1 2 3
a b c

$ paste <(cut -f 2,3 tmp) <(cut -f 1 tmp)
2 3 1
b c a

Shannon -jj Behrens said...

Ah, nice trick. I guess the one constraint is that you have to have the content in a file. I.e. you can't pipe it in.

Heh, that's the first time I've seen someone actually use paste. I saw the man page, but for some reason, I've never seen anyone use it. I also didn't know about the <( ) syntax. Man, I feel like a total shell newb today.

It's funny that what UNIX calls "paste", Python calls "zip".

Steven said...

That is an awesome trick, exactly what I was looking for! Why isn't that documented anywhere??