Chris Brown Chris Brown - 3 months ago 23
Bash Question

${arr[@]} in sed command

#!/bin/sh

arr=(
a
b
c
)
sed "s/abc/${arr[@]}/" file


sh -x this_script.sh show the result with error:

+ arr=(a b c)
+ sed s/abc/a b c/ file
sed: -e expression #1, char 5: unterminated `s' command


it should be:

+ sed 's/abc/a b c/' file


there's already double quotation in this script, why need declare a variable to make it work:

x=${arr[@]}
sed "s/abc/$x/" file

Answer

You can use ${arr[*]} instead of ${arr[@]} to be treated it like a single string:

sed "s/abc/${arr[*]}/" <<< "abc"

a b c