Search code examples
bash

Joining every group of N lines into one with bash


I would like to join every group of N lines in the output of another command using bash.

Are there any standard linux commands i can use to achieve this?

Example:

./command
    46.219464   0.000993    
    17.951781   0.002545    
    15.770583   0.002873    
    87.431820   0.000664    
    97.380751   0.001921    
    25.338819   0.007437

Desired output:

46.219464   0.000993     17.951781  0.002545
15.770583   0.002873     87.431820  0.000664    
97.380751   0.001921     25.338819  0.007437

Solution

  • If your output has consistent number of fields, you can use xargs -n N to group on X elements per line:

    $ ...command... | xargs -n4
    46.219464 0.000993 17.951781 0.002545
    15.770583 0.002873 87.431820 0.000664
    97.380751 0.001921 25.338819 0.007437
    

    From man xargs:

    -n max-args, --max-args=max-args

    Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit.