Search code examples
linuxshellawksedtr

Join N number of lines recursively


How I can achieve below result in shell scripting ?

This is line 1  
This is line 2  
This is line 3  
This is line 4  
This is line 5  
This is line 6  
This is line 7  
This is line 8  
This is line 9  
...  
...  

Desired output :

This is line 1 This is line 2 This is line 3  
This is line 4 This is line 5 This is line 6  
This is line 7 This is line 8 This is line 9  
... ... ....  
... ... ...  

Solution

  • awk is your friend:

    $ awk 'ORS=NR%3?FS:RS' file
    This is line 1   This is line 2   This is line 3  
    This is line 4   This is line 5   This is line 6  
    This is line 7   This is line 8   This is line 9 
    

    Which is the same as:

    $ awk 'ORS=NR%3 ? " " : "\n"' file
    This is line 1   This is line 2   This is line 3  
    This is line 4   This is line 5   This is line 6  
    This is line 7   This is line 8   This is line 9  
    

    Explanation

    If number of record is not multiple of 3, then set the output record separator as space; otherwise, as new line.

    • ORS defines the output record separator.
    • NR defines the number of records (lines in this case).
    • FS defines the fields separators. Default is " " (space).
    • RS defines the records separators. Default is "\n" (new line).

    More info and related examples in Idiomatic awk.