【发布时间】:2010-12-31 19:05:18
【问题描述】:
我有一个包含以下内容的变量:"a b c d e f g h i j k l",您将如何在每个第三个成员之后添加一个逗号符号 (,),使其看起来像这样:"a b c, d e f, g h i, j k l"。
最初我所有的变量数据都存储在一个数组中,所以如果有人知道如何直接操作数组,那就太好了。
提前致谢
【问题讨论】:
我有一个包含以下内容的变量:"a b c d e f g h i j k l",您将如何在每个第三个成员之后添加一个逗号符号 (,),使其看起来像这样:"a b c, d e f, g h i, j k l"。
最初我所有的变量数据都存储在一个数组中,所以如果有人知道如何直接操作数组,那就太好了。
提前致谢
【问题讨论】:
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
【讨论】:
在 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
结果:
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")'
如果您不介意最后一个元素也有逗号,您可以更直接地使用索引(省略设置 $ind 的行):
for i in "${!arr[@]}"; do if (( i%3 == 2 )); then arr[i]+=","; fi; done
如果您不担心数组稀疏:
for ((i=0; i<${#arr[@]}-1; i++)); do if (( i%3 == 2 )); then arr[i]+=","; fi
这与 ghostdog74 的 答案基本相同,只是 Bash 数组是从零开始的,而 awk 字段是从一开始的。
【讨论】:
或者:
$ 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
【讨论】:
这可能对你有用:
echo "a b c d e f g h i j k l" | sed 's/\(\w \w \w\) /\1, /g'
【讨论】: