如何将字符串附加到 Bash 数组的每个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6426142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:40:31  来源:igfitidea点击:

How to append a string to each element of a Bash array?

arraysbash

提问by Richard

I have an array in Bash, each element is a string. How can I append another string to each element? In Java, the code is something like:

我在 Bash 中有一个数组,每个元素都是一个字符串。如何将另一个字符串附加到每个元素?在 Java 中,代码类似于:

for (int i=0; i<array.length; i++)
{
    array[i].append("content");
}

采纳答案by Rajish

Tested, and it works:

经测试,有效:

array=(a b c d e)
cnt=${#array[@]}
for ((i=0;i<cnt;i++)); do
    array[i]="${array[i]}$i"
    echo "${array[i]}"
done

produces:

产生:

a0
b1
c2
d3
e4

EDIT: declaration of the arraycould be shortened to

编辑:声明array可以缩短为

array=({a..e})

To help you understand arrays and their syntax in bash the referenceis a good start. Also I recommend you bash-hackersexplanation.

为了帮助您了解 bash 中的数组及其语法,该参考资料是一个良好的开端。另外我建议你bash-hackers解释。

回答by hal

You can append a string to every array item even without looping in Bash!

即使在 Bash 中没有循环,您也可以将字符串附加到每个数组项!

# cf. http://codesnippets.joyent.com/posts/show/1826
array=(a b c d e)
array=( "${array[@]/%/_content}" )
printf '%s\n' "${array[@]}"

回答by ataraxic

As mentioned by hal

正如 hal 所提到的

  array=( "${array[@]/%/_content}" )

will append the '_content' string to each element.

将 '_content' 字符串附加到每个元素。

  array=( "${array[@]/#/prefix_}" )

will prepend 'prefix_' string to each element

将在每个元素前面加上“prefix_”字符串

回答by Steve Prentice

You pass in the length of the array as the index for the assignment. The length is 1-based and the array is 0-based indexed, so by passing the length in you are telling bash to assign your value to the slot after the last one in the array. To get the length of an array, your use this ${array[@]}syntax.

您传入数组的长度作为赋值的索引。长度是从 1 开始的,数组是从 0 开始索引的,所以通过传递长度,你告诉 bash 将你的值分配给数组中最后一个之后的插槽。要获取数组的长度,请使用此${array[@]}语法。

declare -a array
array[${#array[@]}]=1
array[${#array[@]}]=2
array[${#array[@]}]=3
array[${#array[@]}]=4
array[${#array[@]}]=5
echo ${array[@]}

Produces

生产

1 2 3 4 5