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!

2 Answers 2

1

You simply need to quote elements before inserting them in the array.

I suppose that also you may NOT separate your elements with a comma.

declare -a replacements=("$name" "$description" "$date" "$keywords")
Sign up to request clarification or add additional context in comments.

1 Comment

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!
1

You should quotes in your declaration of array with shell variables:

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

Also note that there must not be commas in shell array initialization.

You can check array content using:

declare -p replacements

Comments

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.