开发者

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

开发者 https://www.devze.com 2023-03-14 15:08 出处:网络
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:

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:

开发者_运维技巧
for (int i=0; i<array.length; i++)
{
    array[i].append("content");
}


As mentioned by hal

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

will append the '_content' string to each element.

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

will prepend 'prefix_' string to each element


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

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


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=({a..e})

To help you understand arrays and their syntax in bash the reference is a good start. Also I recommend you bash-hackers explanation.


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.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消