Bash Scripting – How to Prepend and Append to Each Array Member

arraybashshell-scriptstring

I have an array:

CATEGORIES=(one two three four)

I can prepend to each array member using parameter expansion:

echo ${CATEGORIES[@]/#/foo }

I can append to each array member the same way:

echo ${CATEGORIES[@]/%/ bar}

How can I do both? None of these work:

echo ${CATEGORIES[@]/(.*)/foo \1 bar}
echo ${CATEGORIES[@]/(.*)/foo $1 bar}
echo ${CATEGORIES[@]/(.*)/foo ${BASH_REMATCH[1]} bar}

Best Answer

Depending on what your ultimate aim is, you could use printf:

$ a=(1 2 3)
$ printf "foo %s bar\n" "${a[@]}"
foo 1 bar
foo 2 bar
foo 3 bar

printf re-uses the format string until all the arguments are used up, so it provides an easy way to apply some formatting to a set of strings.