简体   繁体   English

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

[英]How to append a string to each element of a Bash array?

I have an array in Bash, each element is a string. 我在Bash中有一个数组,每个元素都是一个字符串。 How can I append another string to each element? 如何将另一个字符串附加到每个元素? In Java, the code is something like: 在Java中,代码类似于:

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

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[@]}"

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_”字符串

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 array could be shortened to 编辑: array声明可以缩短为

array=({a..e})

To help you understand arrays and their syntax in bash the reference is a good start. 为了帮助您了解bash中的数组及其语法,该参考是一个好的开始。 Also I recommend you bash-hackers explanation. 我也建议您对bash-hackers进行解释。

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. 长度是从1开始的,数组是从0开始的索引,因此通过传递长度,您可以告诉bash将值分配给数组中最后一个之后的插槽。 To get the length of an array, your use this ${array[@]} syntax. 要获取数组的长度,请使用此${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

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

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