Prefix and postfix elements of a bash array

Viewed 16264

I want to pre- and postfix an array in bash similar to brace expansion.

Say I have a bash array

ARRAY=( one two three )

I want to be able to pre- and postfix it like the following brace expansion

echo prefix_{one,two,three}_suffix

The best I've been able to find uses bash regex to either add a prefix or a suffix

echo ${ARRAY[@]/#/prefix_}
echo ${ARRAY[@]/%/_suffix}

but I can't find anything on how to do both at once. Potentially I could use regex captures and do something like

echo ${ARRAY[@]/.*/prefix_$1_suffix}

but it doesn't seem like captures are supported in bash variable regex substitution. I could also store a temporary array variable like

PRE=(${ARRAY[@]/#/prefix_})
echo ${PRE[@]/%/_suffix}

This is probably the best I can think of, but it still seems sub par. A final alternative is to use a for loop akin to

EXPANDED=""
for E in ${ARRAY[@]}; do
    EXPANDED="prefix_${E}_suffix $EXPANDED"
done
echo $EXPANDED

but that is super ugly. I also don't know how I would get it to work if I wanted spaces anywhere the prefix suffix or array elements.

5 Answers

Your last loop could be done in a whitespace-friendly way with:

EXPANDED=()
for E in "${ARRAY[@]}"; do
    EXPANDED+=("prefix_${E}_suffix")
done
echo "${EXPANDED[@]}"
Related