Shell – Use paste with row-major input

pasteshell-scripttext processing

I can create a file with multiple columns from a single-column input via paste like this:

some_command | paste - -

This works when some_command produces the data in column-major format. In other words, the input

1
2
3
4

results in the output

1   2
3   4

However, I want the opposite, i.e. I want

1   3
2   4

Background: I want to collect all N’th columns from M files into one aggregate file. I tried doing this via:

cut -f 5 "${files[@]}" | paste - - - - - …

(with M -s). But as mentioned before, this doesn’t work, as paste expects column-major input. I can’t help but think that there should be a coreutils (or pure Bash) solution for this.

Best Answer

If I correctly understand the question, you could try with pr:

cut -f 5 "${files[@]}" | pr -5 -s' ' -t -l 40

where -5 is the number of columns, -s' ' is the separator (space) and -l 40 is the page length (40 lines).


Without coreutils, one could use split to create pieces of N lines:

split -lN infile

or

some_command | split -lN

and then paste them together:

paste x* > outfile
rm x*
Related Question