In Bash:
arr=(a b c d e f g h i j k l)
ind=("${!arr[@]}") # get the indices of the array (handles sparse arrays)
ind=(${ind[@]:0:${#ind[@]} - 1}) # strip off the last one
# add commas to every third one (but the last)
for i in "${ind[@]}"; do if (( i%3 == 2 )); then arr[i]+=","; fi; done
echo "${arr[@]}" # print the array
declare -p arr # dump the array
Results in:
a b c, d e f, g h i, j k l
declare -a arr='([0]="a" [1]="b" [2]="c," [3]="d" [4]="e" [5]="f," [6]="g" [7]="h" [8]="i," [9]="j" [10]="k" [11]="l")'
If you don't mind the last element also having a comma, you can use the indices more directly (omit the lines that set $ind
):
for i in "${!arr[@]}"; do if (( i%3 == 2 )); then arr[i]+=","; fi; done
If you're not worried about the array being sparse:
for ((i=0; i<${#arr[@]}-1; i++)); do if (( i%3 == 2 )); then arr[i]+=","; fi
which is basically the same as ghostdog74's answer except that Bash arrays are zero-based and awk fields are one-based.