vektor
vektor

Reputation: 2926

Put every N rows of input into a new column

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?

Upvotes: 9

Views: 3310

Answers (3)

Steve
Steve

Reputation: 54422

Here's how I'd do it with awk:

awk -v n=5 '{ c++ } c>n { c=1 } { a[c] = (a[c] ? a[c] FS : "") $0 } END { for (i=1;i<=n;i++) print a[i] }'

Some simple testing:

seq 21 | awk -v n=5 '{ c++ } c>n { c=1 } { a[c] = (a[c] ? a[c] FS : "") $0 } END { for (i=1;i<=n;i++) print a[i] | "column -t" }'

Results:

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

And another:

seq 40 | awk -v n=6 '{ c++ } c>n { c=1 } { a[c] = (a[c] ? a[c] FS : "") $0 } END { for (i=1;i<=n;i++) print a[i] | "column -t" }'

Results:

1  7   13  19  25  31  37
2  8   14  20  26  32  38
3  9   15  21  27  33  39
4  10  16  22  28  34  40
5  11  17  23  29  35
6  12  18  24  30  36

Upvotes: 3

Chris Seymour
Chris Seymour

Reputation: 85815

Using a little known gem pr:

$ seq 20 | pr -ts' ' --column 4
1 6 11 16
2 7 12 17
3 8 13 18
4 9 14 19
5 10 15 20

Upvotes: 15

Kent
Kent

Reputation: 195109

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 

Upvotes: 6

Related Questions