简体   繁体   English

Perl用包含空格和双引号的字符串替换字符串

[英]Perl to substitute string with a string containing spaces and double quotes

My bash script builds a string variable $arrayLMEs , containing a string like: 我的bash脚本构建了一个字符串变量$arrayLMEs ,其中包含如下字符串:

var availableTags=[ "01 East Bering Sea", "02 Gulf of Alaska"];

I need to put this string in a javascript code, to replace a placeholder. 我需要将此字符串放在javascript代码中,以替换占位符。 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. 但是实际上该命令抱怨,因为在字符串中找到了双引号,这使bash命令混乱,从而使perl命令混乱。

How can I fix the command to keep the spaces and double quotes? 如何修复保留空格和双引号的命令?

Use the -s switch to pass the variable to perl: 使用-s开关将变量传递给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 . -var="$arrayLMEs"设置一个perl变量,其值为您的shell变量$arrayLMEs的值。

Alternatively, you could use awk: 或者,您可以使用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. 使用awk的一个很好的副作用是替换是一个简单的字符串,因此原始字符串中的元字符将不会被解释。

For the record, I found a workaround (but not as good as Tom Fenech's solution). 作为记录,我找到了一种解决方法(但不如Tom Fenech的解决方案好)。

  1. Save the variable in a file 将变量保存在文件中

    echo $arrayLMEs > tmpfile

  2. use sed to paste the file content into the target file 使用sed将文件内容粘贴到目标文件中

    sed -i '/PLACEHOLDER/{ r tmpfile d }' filename

I suppose that it is quite robust. 我认为它非常强大。 Downside: forces to create another file on the fly. 缺点:强制动态创建另一个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM