Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reordering columns with AWK

I need to reorder the columns of this (tab-separated) data:

   1 cat    plays
   1 dog    eats
   1 horse  runs
   1 red    dog
   1 the    cat
   1 the    cat

so that is prints like:

cat plays   1
dog eats    1
horse   runs    1
red dog 1
the cat 2

i have tried:

sort [input] | uniq -c | awk '{print $2 "\t" $3 "\t" $1}' > [output]

and the result is:

1   cat 1
1   dog 1
1   horse   1
1   red 1
2   the 1

Can anyone give me some insight on what is going wrong? Thank you.

like image 960
owwoow14 Avatar asked Sep 22 '13 17:09

owwoow14


2 Answers

Since the output of cat input | sort | uniq -c is:

   1    1 cat    plays
   1    1 dog    eats
   1    1 horse  runs
   1    1 red    dog
   2    1 the    cat

you need something like:

cat input | sort | uniq -c | awk '{print $3 "\t" $4 "\t" $1}'

And we can also indicate the output field separator in awk:

cat input | sort | uniq -c | awk -v OFS="\t" '{print $3,$4,$1}'
like image 59
pNre Avatar answered Sep 28 '22 14:09

pNre


uniq -c adds an extra column. This should give you the output you want:

$ sort file | uniq -c | awk '{print $3 "\t" $4 "\t" $1}'
cat     plays   1
dog     eats    1
horse   runs    1
red     dog     1
the     cat     2
like image 27
user000001 Avatar answered Sep 28 '22 14:09

user000001