How can I prepend and append to each member of an array? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How can I prepend and append to each member of an array? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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}

Answer

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

$ a=(1 2 3)
$ printf "foo %s barn" "${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.

We are here to answer your question about How can I prepend and append to each member of an array? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji