0

I'm trying to use the next array's elements to replace some strings in a file:

declare -a replacements=($name, $description, $date, $keywords)

By using the search terms in this array:

declare -a searchs=("a.name", "a.description", "a.date", "a.keywords")

The problem is that some variables (description, for example) have whitespaces in them:

declare description = "My name is Jonah"

Which casuses a weird behaviour on the next piece of code:

for ((i = 0; i < ${#searchs[@]}; i++))
do
    sed -i -e "s/${searchs[$i]}/${replacements[$i]}/g" "./${directory}/data.txt"
done

The for loops uses every word in the string as a replacement instead of the whole string.

Is there a way to fix this error? Thanks in advance!

  • 1
    Sorry didn't mean to auto close. The commas in your array declaration are invalid however you also need to quote the variables. declare -a replacements=("$name" "$description" "$date" "$keywords") – jesse_b Mar 12 '20 at 17:12
  • You might also want to use an associative array for this. – jesse_b Mar 12 '20 at 17:22
  • Commas where an error of mine while writing the code in here. I didn't want to use the actual code. Either way, the quoting is indeed the solution. Thanks a lot! – Enrique Bermúdez Mar 12 '20 at 17:29

0 Answers0