Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

bash

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"); } 
like image 793
Richard Avatar asked Jun 21 '11 13:06

Richard


People also ask

How do you append to an array in bash?

To append element(s) to an array in Bash, use += operator. This operator takes array as left operand and the element(s) as right operand. The element(s) must be enclosed in parenthesis. We can specify one or more elements in the parenthesis to append to the given array.

How do I append to a variable in bash?

The += Operator in Bash Bash is a widely used shell in Linux, and it supports the '+=' operator to concatenate two variables. As the example above shows, in Bash, we can easily use the += operator to concatenate string variables.


1 Answers

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

like image 100
ataraxic Avatar answered Sep 28 '22 14:09

ataraxic