Search code examples
linuxshellloopsformattingseq

Shellscript: Is it possible to format seq to display n numbers per line?


Is it possible to format seq in a way that it will display the range desired but with N numbers per line?

Let say that I want seq 20 but with the following output:

1 2 3 4 5        
6 7 8 9 10        
11 12 13 14 15        
16 17 18 19 20        

My next guess would be a nested loop but I'm not sure how... Any help would be appreciated :)


Solution

  • Use can use awk to format it as per your needs.

    $ seq 20 | awk '{ORS=NR%5?FS:RS}1'
    1 2 3 4 5
    6 7 8 9 10
    11 12 13 14 15
    16 17 18 19 20
    

    ORS is awk's built-in variable which stands for Output Record Separator and has a default value of \n. NR is awk's built-in variable which holds the line number. FS is built-in variable that stands for Field Separator and has the default value of space. RS is built-in variable that stands for Record Separator and has the default value of \n.

    Our action which is a ternary operator, to check if NR%5 is true. When it NR%5 is not 0 (hence true) it uses FS as Output Record Separator. When it is false we use RS which is newline as Output Record Separator.

    1 at the end triggers awk default action that is to print the line.