Search code examples
unixtranspose

Transpose one column to rows based on another column values


I want to transpose a column in several smaller parts based on another column's values e.g.

1 ID1  V1  
2 ID1  V2  
3 ID1  V3  
4 ID2  V4  
5 ID2  V5  
6 ID3  V6  
7 ID3  V7  
8 ID3  V8  
9 ID3  V9  

I wish to have all V values for each ID to be in one row e.g.

ID1 V1 V2 V3  
ID2 V4 V5  
ID3 V6 V7 V8 V9

Each id has different number of rows to transpose as shown in the example. If it is easier to use the serial number column to perform this then that is fine too.

Can anyone help ?


Solution

  • Here is a simple awk one-liner to do the trick:

    awk '1 {if (a[$2]) {a[$2] = a[$2]" "$3} else {a[$2] = $3}} END {for (i in a) { print i,a[i]}}' file.txt
    

    Output:

    ID1 V1 V2 V3
    ID2 V4 V5
    ID3 V6 V7 V8 V9