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

ArraysBash

Arrays Problem Overview


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");
}

Arrays Solutions


Solution 1 - Arrays

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

Solution 2 - Arrays

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

Solution 3 - Arrays

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.

Solution 4 - Arrays

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichardView Question on Stackoverflow
Solution 1 - ArraysataraxicView Answer on Stackoverflow
Solution 2 - ArrayshalView Answer on Stackoverflow
Solution 3 - ArraysRajishView Answer on Stackoverflow
Solution 4 - ArraysSteve PrenticeView Answer on Stackoverflow