Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using awk to transpose column to row

Tags:

awk

I have an input data file:

anim   gent
FZ543     1
FZ543     2
FZ543     3
FZ543     1
FZ547     4
FZ547     3
FZ547     3
FZ547     1

I wanted to transpose these data to:-

anim     gent
FZ543     1 2 3 1
FZ547     4 3 3 1

In other words, I wanted to transpose elements from vertical to horizontal. I can used AWK Comand

Thanks for your atention.

like image 534
Johanna Ramirez Avatar asked Nov 29 '12 21:11

Johanna Ramirez


2 Answers

awk 'NR==1{print} NR>1{a[$1]=a[$1]" "$2}END{for (i in a){print i " " a[i]}}' file

OUTPUT

anim   gent
FZ543  1 2 3 1
FZ547  4 3 3 1
like image 163
Gilles Quenot Avatar answered Jan 01 '23 13:01

Gilles Quenot


$ awk '$1 != prev{printf "%s%s",ors,$1; ors=ORS; ofs="\t"} {printf "%s%s",ofs,$2; ofs=OFS; prev=$1} END{print ""}' file
anim    gent
FZ543   1 2 3 1
FZ547   4 3 3 1
like image 37
Ed Morton Avatar answered Jan 01 '23 14:01

Ed Morton