Shell: Create a comma separated string
I recently needed to generate a string with comma separated values, based on iterating a range of numbers.
e.g. we should get the following output where n = 3
foo-0,foo-1,foo-2
I only had the shell available to me so I couldn’t shell out into Python or Ruby for example. That means it’s bash scripting time!
If we want to iterate a range of numbers and print them out on the screen we can write the following code:
n=3
for i in $(seq 0 $(($n > 0? $n-1: 0))); do
echo "foo-$i"
done
foo-0
foo-1
foo-2
Combining them into a string is a bit more tricky, but luckily I found a great blog post by Andreas Haupt which shows what to do. Andreas is solving a more complicated problem than me but these are the bits of code that we need from the post.
n=3
combined=""
for i in $(seq 0 $(($n > 0? $n-1: 0))); do
token="foo-$i"
combined="${combined}${combined:+,}$token"
done
echo $combined
foo-0,foo-1,foo-2
This won’t work if you set n<0 but that’s ok for me! I’ll let Andreas explain how it works:
-
${combined:+,} will return either a comma (if combined exists and is set) or nothing at all.
-
In the first invocation of the loop combined is not yet set and nothing is put out.
-
In the next rounds combined is set and a comma will be put out.
We can see how it in action by printing out the value of $combined after each iteration of the loop:
n=3
combined=""
for i in $(seq 0 $(($n > 0 ? $n-1: 0))); do
token="foo-$i"
combined="${combined}${combined:+,}$token"
echo $combined
done
foo-0
foo-0,foo-1
foo-0,foo-1,foo-2
Looks good to me!
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.