i would like to append each array element into this string,
arr=(col1 col2 col3)
str="to/path/${arr[@]}
output would be like this
to/path/col1
to/path/col2
to/path/col3
do you have any idea how?
Using bash parameter expansion:
arr=(col1 col2 col3)
str=${arr[@]/#/\/path\/to\/}
echo "$str"
/path/to/col1 /path/to/col2 /path/to/col3
As Charles indicates, we're converting from an array to a string, which has negative consequences if you want to iterate over the result. In that case, try this:
arr=( "col 1" "col 2" "col 3" )
newarr=()
for elem in "${arr[@]}"; do
newarr+=( "/path/to/$elem" )
done
printf "%s\n" "${newarr[@]}"
arr2=( "${arr[@]/#//path/to/}" ) -- without the backslash escaping -- seems to be what works in generating a new array with each element prefixed; I'll admit to being a bit surprised.
printf 'to/path/%s\n' "${arr[@]}"will emit your desired output, while handling the array as an array the whole time, rather than trying to convert it to a string.