Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining every group of N lines into one with bash

Tags:

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
like image 797
Otrebor Avatar asked Sep 22 '14 11:09

Otrebor


2 Answers

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.

like image 72
fedorqui 'SO stop harming' Avatar answered Sep 28 '22 08:09

fedorqui 'SO stop harming'


Seems like you're trying to join every two lines with the delimiter \t(tab). If yes then you could try the below paste command,

command | paste -d'\t' - -

If you want space as delimiter then use -d<space>,

command | paste -d' ' - -
like image 41
Avinash Raj Avatar answered Sep 28 '22 07:09

Avinash Raj