Put all N lines of input in a new column

In bash, the given input is

1
2
3
4
5
6
7
8
...

      

And N

for example 5, I need an output

1  6  11
2  7  12
3  8  ...
4  9
5  10 

      

How to do it?

+3


source to share


3 answers


replace 5 with the 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 is only for generating a sequence of numbers for testing. You don't need this in your real job.



EDIT

as sudo_O pointed out, I add a 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 

      

+4


source


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

      

+9


source


This is how I would 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 tests:

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 further:

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

      

+2


source







All Articles