Reputation: 902
My bash script builds a string variable $arrayLMEs
, containing a string like:
var availableTags=[ "01 East Bering Sea", "02 Gulf of Alaska"];
I need to put this string in a javascript code, to replace a placeholder. I was thinking to use something like:
perl -i -pe 's/PLACEHOLDER/'"${arrayLMEs}"'/' filename
But actually the command complains, because of the double quotes found in the string, which are messing up the bash command and in consequence the perl command.
How can I fix the command to keep the spaces and double quotes?
Upvotes: 0
Views: 663
Reputation: 74605
Use the -s
switch to pass the variable to perl:
perl -spe 's/PLACEHOLDER/$var/' -- -var="$arrayLMEs" filename
The --
signifies the end of the command line arguments. -var="$arrayLMEs"
sets a perl variable with the value of your shell variable $arrayLMEs
.
Alternatively, you could use awk:
awk -v var="$arrayLMEs" '{sub(/PLACEHOLDER/, var)}1' filename
A nice side-effect of using awk is the replacement is a simple string, so metacharacters in the original string won't be interpreted.
Upvotes: 4
Reputation: 902
For the record, I found a workaround (but not as good as Tom Fenech's solution).
Save the variable in a file
echo $arrayLMEs > tmpfile
use sed to paste the file content into the target file
sed -i '/PLACEHOLDER/{
r tmpfile
d
}' filename
I suppose that it is quite robust. Downside: forces to create another file on the fly.
Upvotes: 1