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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With