tags:

views:

211

answers:

3

I have a variable with the following contents: "a b c d e f g h i j k l", how would you go about adding a comma sign (,) after each third member so it looks like this: "a b c, d e f, g h i, j k l".

Initially all my variable data is stored in an array so if anyone knows how to directly manipulate the array, it would be great.

Thanks in advance

+4  A: 

awk

$ echo "a b c d e f g h i j k l" | awk '{for(i=1;i<NF;i++)if(i%3==0){$i=$i","}  }1'
a b c, d e f, g h i, j k l
ghostdog74
perfect, just what I needed, thank you for the fast reply :)
f10bit
+2  A: 

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.

Dennis Williamson
+1  A: 

Or:

$ a=(a b c d e f g h i j k l)
$ printf '%s\n' "${a[@]}"|paste -sd'  ,'
a b c,d e f,g h i,j k l
radoulov