Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Bash在变量或数组的每三个字段后插入逗号(,)?_Arrays_Bash_Sed_Awk - Fatal编程技术网

Arrays Bash在变量或数组的每三个字段后插入逗号(,)?

Arrays Bash在变量或数组的每三个字段后插入逗号(,)?,arrays,bash,sed,awk,Arrays,Bash,Sed,Awk,我有一个包含以下内容的变量:“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

我有一个包含以下内容的变量:
“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
$echo“a b c d e f g h i j k l”| awk'{for(i=1;i在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=0; i<${#arr[@]}-1; i++)); do if (( i%3 == 2 )); then arr[i]+=","; fi
((i=0;i或:


这可能适合您:

 echo "a b c d e f g h i j k l" | sed 's/\(\w \w \w\) /\1, /g'
$ 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'