简体   繁体   English

使用 for 循环将变量连接成由逗号分隔的单个变量

[英]concatenate variable into single variable separated by comma with for loop

I want to add the values to a variable, separated by comma, using for loop.我想使用 for 循环将值添加到变量中,以逗号分隔。 First values should remain first and so on.第一个值应该保持在第一个,依此类推。

for ((i=0; i<${#MYARRAY[@]}; i++));
do
  ALL=$ALL$MYARRAY$i,
done
echo $ALL

I expect the output val1,val2,val3 but the actuel output is val1,val2,val3,我期望输出 val1,val2,val3 但实际输出是 val1,val2,val3,

How to avoid the comma after the last value?如何避免最后一个值后面的逗号?

https://www.tldp.org/LDP/abs/html/string-manipulation.html is a good source. https://www.tldp.org/LDP/abs/html/string-manipulation.html是一个很好的来源。 Insert the following line after the loop. 循环后插入以下行。

ALL=${ALL%,}

In this example, the first iteration does not put a comma in $ALL . 在此示例中,第一次迭代不会在$ALL放置逗号。 In the following iteration, a comma is placed before the value. 在下面的迭代中,逗号放在值之前。 This way, there won't be any comma at the end of the output string. 这样,输出字符串末尾就不会有任何逗号。

MYARRAY=(val val val)
for (( i=0; i<${#MYARRAY[@]}; i++ ))
do
    if [ $i == 0 ]
    then
        ALL=$ALL$MYARRAY$i
    else
        ALL=$ALL,$MYARRAY$i
    fi
done
echo $ALL

This is exactly what the [*] construct is for: 这正是[*]构造的用途:

myarray=(val1 val2 val3 val4)

oldIFS="$IFS"

IFS=',' 
echo "${myarray[*]}"

IFS="$oldIFS"

gives: 得到:

val1,val2,val3,val4

I am using lowercase myarray because uppercase should be reserved for system (bash) variables. 我使用小写myarray因为大写应该保留为系统(bash)变量。

Note that "${myarray[*]}" must be inside double-quotes, otherwise you do not get the join magic. 请注意, "${myarray[*]}" 必须在双引号内,否则您无法获得连接魔法。 The elements are joined by the first character of IFS , which by default is a space. 元素由IFS的第一个字符连接,默认情况下是一个空格。

只需在for循环后添加三个语句中的一个:

  1. ALL=${ALL%,}

  2. ALL=${ALL::-1}

  3. ALL=${ALL%?}

Another option is with the translate ( tr ) command.另一种选择是使用 translate ( tr ) 命令。 For example:例如:

$ myarray=(val1 val2 val3 val4)

$ echo ${myarray[*]}
val1 val2 val3 val4

$ myarray=$(echo ${myarray[*]} | tr ' ' ,)     # Replace space with ','

$ echo $myarray                                # Gives what you need
val1,val2,val3,val4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM