awk transpose row into 2 field column

Need to transpose every 2 fields of a row into a single 2 field column.

input

 4 135 114 76 217 30 346 110
 5 185 115 45 218 85 347 125
 6 85 116 130 220 65 352 95
 11 30 117 55 221 42 355 75
 16 72 118 55 224 37 357 430
 17 30 119 55 225 40 358 62
 21 52 120 65 232 480 360 180
....
....

desired output

4    135
5    185
6    85
11    30
16    72
17    30
21    52
...
...
114 76
115 45
116 130
...
...
217 30
awk '{ for(N=1; N<=NF; N+=2) print $N, $(N+1); }' filename > outfile
1 Like

nevermind

Wow couldn't be faster, and its working!

Actually, it's not, I just realized you wanted it pivoted in a different direciton. Sorry.

awk '{ D[++L]=$0 }
(!MAX) || (NF>MAX) { MAX=NF }

END {
        for(M=1; M<=MAX; M+=2)
        for(N=1; N<=L; N++)
        {
                $0=D[N];
                print $M, $(M+1);
        }
}' datafile
sed 's/\([0-9]\{1,\} [0-9]\{1,\}\)/\1\n/g' infile | sort -g -k1

or

xargs -n 2 < infile | sort -g -k1

Yes the sorting works, though when the input has different number of columns, the script writes for each missing column a blank line. Isn't the asort function more concise?

input:

 1 450 129 70 229 130 296 160
 5 65 131 675 230 75
 6 55 132 45
 11 48

output:

1 450
5 65
6 55
11 48
129 70
131 675
132 45
 
229 130
230 75
 
 
296 160
 
 
 

Hi Combo,

Thanks for this, still I need to understand this logic:

  1. First you are putting every row in array
D 

start with

D[1] 
  1. Then you are setting variable MAX. Are you checking this for every line. What is the value of
MAX

.

END

section will execute finally when everthing is done right. Please explain.

awk '{ D[++L]=$0 }
(!MAX) || (NF>MAX) { MAX=NF }
END {
        for(M=1; M<=MAX; M+=2)
        for(N=1; N<=L; N++)
        {
                $0=D[N];
                print $M, $(M+1);
        }
}' datafile