Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prepend and append a string to all elements of an array without using a temporary variable

Tags:

bash

Is there a way to both prepend and append a string to all elements of an array without using a temporary variable, i.e. only using shell parameter expansion?

Having an array

a=(1 2 3)

we prepend a string to every element, e.g. "[" as follows

$ echo ${a[@]/#/[}
[1 [2 [3

and we apend a string to every element, e.g. "]" as follows

$ echo ${a[@]/%/]}
1] 2] 3]

I we want to both prepend "[" and append "]" (i.e. kind of enclose) we do something like the following (but we need a temp variable tmp):

$ a=(1 2 3)
tmp=(${a[@]/#/[})
echo ${tmp[@]/%/]}
[1] [2] [3]

Is there something like the following?

# the following is not working!!!
${             /%/]}
  ^^^^^^^^^^^^^
  (${a[@]/#/[})
# embed the resulting array of the prepending parameter expansion
like image 452
wolfrevo Avatar asked Mar 13 '26 14:03

wolfrevo


2 Answers

If you've got Bash 5.2 (released in September 2022) you can do:

echo "${a[@]/*/[&]}"

This is due to the new patsub_replacement option, which is enabled by default. See The Shopt Builtin section of the Bash Reference Manual.

like image 191
pjh Avatar answered Mar 15 '26 09:03

pjh


You can't use just parameter expansion to achieve that. But you can use e.g. printf:

a=(1 2 3)
printf '[%s] ' "${a[@]}"
echo

printf will output the formatted string for each element of the array.

like image 20
choroba Avatar answered Mar 15 '26 09:03

choroba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!