Put every N rows of input into a new column

awk, bash, linux, shell, unix

Solution

replace 5 in following script with your number.

seq 20|xargs -n5| awk '{for (i=1;i<=NF;i++) a[i,NR]=$i; }END{
    for(i=1;i<=NF;i++) {for(j=1;j<=NR;j++)printf a[i,j]" "; print "" }}' 

output:

1 6 11 16 
2 7 12 17 
3 8 13 18 
4 9 14 19 
5 10 15 20

note `seq 20` above there is just for generating the number sequence for testing. You don't need it in your real work.

EDIT

as pointed out by sudo_O, I add an pure awk solution:

 awk -vn=5 '{a[NR]=$0}END{ x=1; while (x<=n){ for(i=x;i<=length(a);i+=n) printf a[i]" "; print ""; x++; } }' file

test

kent$  seq 20| awk -vn=5 '{a[NR]=$0}END{ x=1; while (x<=n){ for(i=x;i<=length(a);i+=n) printf a[i]" "; print ""; x++; } }'     
1 6 11 16 
2 7 12 17 
3 8 13 18 
4 9 14 19 
5 10 15 20 

kent$  seq 12| awk -vn=5 '{a[NR]=$0}END{ x=1; while (x<=n){ for(i=x;i<=length(a);i+=n) printf a[i]" "; print ""; x++; } }'     
1 6 11 
2 7 12 
3 8 
4 9 
5 10 

Problem

In bash, given input ``` 1 2 3 4 5 6 7 8 ... ``` And `N` for example 5, I want the output ``` 1 6 11 2 7 12 3 8 ... 4 9 5 10 ``` How do I do this?

Original source