Shell: Create a Comma Separated String
In this quick tutorial, we go over how to use Shell scripting in a pinch to create working strings of code that will help us make basic calculations.
Join the DZone community and get the full member experience.
Join For FreeI 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 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 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!
Published at DZone with permission of Mark Needham, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments