1

I have an array of an UNKNOWN number of elements that i want to print in this format: item1-item2,item3-item4,item5-item6...

forexample: if myarray contains these element: 0 9 11 20 22 31 33 42

I want to populate the output as:

0-9,11-20,22-31,33-42

so far, im only able to print it out by separating the elements with a comma. But i need to separate it in a ranges:

$ printf "%s-" "${myarray[@]}"
0-9-11-20-22-31-33-42-44

thank you for any hint.

3

You can simply use printf "%d-%d," "${myarray[@]}":

$ printf "%d-%d," "${myarray[@]}"
0-9,11-20,22-31,33-42,$

However, that lacks a final newline and has an extra comma, so you could extend it to:

$ echo $(printf "%d-%d," "${myarray[@]}") | sed 's/,$//'
0-9,11-20,22-31,33-42

This will fail if your array doesn't have an even number of elements (it will print an extra 0):

$ myarray=(0 9 11 20 22 31 33)
$ echo $(printf "%d-%d," "${myarray[@]}") | sed 's/,$//'
0-9,11-20,22-31,33-0

You might prefer to use %s instead which just leaves the last one empty:

$ echo $(printf "%s-%s," "${myarray[@]}") | sed 's/,$//'
0-9,11-20,22-31,33-

And finally remove the trailing -:

$ echo $(printf "%s-%s," "${myarray[@]}") | sed 's/[,-]*$//' 
0-9,11-20,22-31,33
  • Thanks for the cool tricks. They will come in handy. – WinEunuuchs2Unix Jul 8 at 19:40
  • Very simple and worked great. I was over thinking it. Thank you very much! – Samy Jul 9 at 20:07
1

terdon's answer is very good. A (probably) slower, pure-bash approach would be

a=(0 9 11 20 22 31 33 42)
pairs=()
for ((i = 0; i < ${#a[@]}; i += 2)); do
    pairs+=( "${a[i]}-${a[i+1]}" )
done
result=$(IFS=,; echo "${pairs[*]}")
echo "$result"
0-9,11-20,22-31,33-42

Or

result=$(
    for ((i = 0; i < ${#a[@]}; i += 2)); do
        echo "${a[i]}-${a[i+1]}"
    done | paste -sd,
)

Or (I can't resist this kind of thing)

sep="-"
for elem in "${a[@]}"; do
    printf "%s%s" "$elem" $sep
    [[ $sep == "-" ]] && sep="," || sep="-"
done | sed 's/.$//'
  • Shell TIMTOWTDI! Nice :) – terdon Jul 9 at 20:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.