0

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?

2
  • 4
    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. Commented Jun 21, 2017 at 2:04
  • thanks, this solved my problem Commented Jun 21, 2017 at 2:46

1 Answer 1

4

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[@]}"
Sign up to request clarification or add additional context in comments.

1 Comment

Huh. 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.