CLI tip 15: text generation with printf and brace expansion
You can use brace expansion for generating a sequence of numbers and alphabets. printf
helps you to display multiple arguments using the same format specifier. For example:
$ echo {1..3}
1 2 3
$ echo {1..2}{a..b}
1a 1b 2a 2b
$ printf '%s\n' apple banana cherry
apple
banana
cherry
Combining the two, you can generate multiple lines of text. Here are some examples:
$ printf '%s\n' id_{3..1}
id_3
id_2
id_1
$ printf '%s\n' item_{100..120..4}
item_100
item_104
item_108
item_112
item_116
item_120
Here's a practical example:
# the string before %.s is repeated based on the number of arguments
$ printf 'x %.s' a b c
x x x
$ printf -- '- %.s' {1..5}
- - - - -
# same as: seq 10 | paste -d, - - - - -
$ seq 10 | paste -d, $(printf -- '- %.s' {1..5})
1,2,3,4,5
6,7,8,9,10
$ n=5
$ seq 10 | paste -d, $(printf -- '- %.s' $(seq $n))
1,2,3,4,5
6,7,8,9,10
$ n=2
$ seq 10 | paste -d, $(printf -- '- %.s' $(seq $n))
1,2
3,4
5,6
7,8
9,10
See this stackoverflow thread for other alternatives, avoiding printf
for large numbers, etc.
Video demo:
See also my Linux Command Line Computing ebook.