17

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
Otrebor
  • 416
  • 4
  • 12
  • Between `paste`, `pr`, `sed`, `awk`, `xargs` and pure `bash`, [here is a comparission bench about *How to merges 16 lines*](https://stackoverflow.com/a/47348104/1765658) – F. Hauri - Give Up GitHub Dec 06 '21 at 12:10

2 Answers2

20

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 2
    `cmd... | paste -d " " - - - -` do same job **a lot faster**! Please have a look at *... do a little bench* paragraph on [Merge 16 lines into one line](https://stackoverflow.com/a/47348104/1765658)! I compare 6 different way for this, `xargs` is the worst!! – F. Hauri - Give Up GitHub Jan 14 '20 at 07:58
  • 1
    this wins for speed of typing tho :) – Goblinhack Jan 26 '23 at 13:40
  • @Goblinhack No, `pr -at2` is clearly shorter in chars **and** in executrion time!! Again: read [this post](https://stackoverflow.com/a/47348104/1765658) – F. Hauri - Give Up GitHub Aug 31 '23 at 06:05
15

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' ' - -
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274