Perl to substitute string with a string containing spaces and double quotes

644 views Asked by At

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?

2

There are 2 answers

1
Tom Fenech On BEST ANSWER

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.

0
Bruno von Paris On

For the record, I found a workaround (but not as good as Tom Fenech's solution).

  1. Save the variable in a file

    echo $arrayLMEs > tmpfile

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