Search code examples
bashgnu-coreutils

Joining lines, modulo the number of records


Say my stream is x*N lines long, where x is the number of records and N is the number of columns per record, and is output column-wise. For example, x=2, N=3:

1
2
Alice
Bob
London
New York

How can I join every line, modulo the number of records, back into columns:

1   Alice   London
2   Bob     New York

If I use paste, with N -s, I get the transposed output. I could use split, with the -l option equal to N, then recombine the pieces afterwards with paste, but I'd like to do it within the stream without spitting out temporary files all over the place.

Is there an "easy" solution (i.e., rather than invoking something like awk)? I'm thinking there may be some magic join solution, but I can't see it...


EDIT Another example, when x=5 and N=3:

1
2
3
4
5
a
b
c
d
e
alpha
beta
gamma
delta
epsilon

Expected output:

1   a   alpha
2   b   beta
3   c   gamma
4   d   delta
5   e   epsilon

Solution

  • You are looking for pr to "columnate" the stream:

    pr -T -s$'\t' -3 <<'END_STREAM'
    1
    2
    Alice
    Bob
    London
    New York
    END_STREAM
    
    1       Alice   London
    2       Bob     New York
    

    pr is in coreutils.