Bash: How to Add String to Each Element in an Array


Often you may want to use Bash to add a string to each element in an array.

You can use the following methods to do so:

Method 1: Append String to End of Each Element in Array

my_array=( "${my_array[@]/%/_team}" )

This particular example will append the string _team to the end of each element in the array named my_array.

Method 2: Prepend String to Beginning of Each Element in Array

my_array=( "${my_array[@]/#/team_}" )

This particular example will prepend the string team_ to the beginning of each element in the array named my_array.

The following examples show how to use each of these methods in practice.

Example 1: Append String to End of Each Element in Array

Suppose that we create the following array in Bash named my_array that contains the names of various basketball teams:

my_array=(Mavs Celtics Cavs Hawks Nets)

We can use the following syntax to append the string _team to the end of each element in this array:

my_array=( "${my_array[@]/%/_team}" )
echo "${my_array[@]}"

The following screenshot shows how to use this syntax in practice:

Bash add string to end of each element in array

Note that when we use the echo command to view each of the elements in the array named my_array we can see that the string _team has been added to the end of each element in the array.

Example 2: Prepend String to Beginning of Each Element in Array

Once again, suppose that we create the following array in Bash named my_array that contains the names of various basketball teams:

my_array=(Mavs Celtics Cavs Hawks Nets)

We can use the following syntax to prepend the string team_ to the beginning of each element in this array:

my_array=( "${my_array[@]/#/team_}" )
echo "${my_array[@]}"

The following screenshot shows how to use this syntax in practice:

Bash prepend string to beginning of each element in array

Note that when we use the echo command to view each of the elements in the array named my_array we can see that the string team_ has been prepended to the beginning of each element in the array.

Feel free to use similar syntax to add a specific string to each element in your own array.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Select Random Element from an Array
Bash: How to Split a String and Get Last Element
Bash: How to Remove Last Element from Array

Leave a Reply