开发者

Bash insert a comma (,) after every third field of a variable or array?

I have a variable with the following contents: "a b c d e f g h i j k l", how would y开发者_运维知识库ou 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


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


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.


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


This might work for you:

 echo "a b c d e f g h i j k l" | sed 's/\(\w \w \w\) /\1, /g'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜