[英]Perl CLI in-place string substitution/replacement of multiple lines with special characters
I'm trying to write a CLI command to change the contents of a config file.我正在尝试编写一个 CLI 命令来更改配置文件的内容。
The config file has these lines:配置文件有以下几行:
JAVA_OPTS="$JAVA_OPTS -XX:+UseParNewGC"
JAVA_OPTS="$JAVA_OPTS -XX:+UseConcMarkSweepGC"
I want to change those two lines to this one line:我想将这两行更改为这一行:
JAVA_OPTS="$JAVA_OPTS -XX:+UseG1GC"
I want to replace multiple lines, so I'm trying to use Perl to do that.我想替换多行,所以我尝试使用 Perl 来做到这一点。
perl -i -pe 's/JAVA_OPTS="\$JAVA_OPTS -XX:\+UseParNewGC"\nJAVA_OPTS="\$JAVA_OPTS -XX:\+UseConcMarkSweepGC"/JAVA_OPTS="$JAVA_OPTS -XX:+UseG1GC"/' name-of-file.sh
However, this command doesn't change the file.但是,此命令不会更改文件。 I'm guessing the regular expression doesn't match.
我猜正则表达式不匹配。 I don't know why.
我不知道为什么。 I've tried several variations of the command and I've tried escaping and double-escaping the
$
and +
symbols in the match string, but nothing I do makes a difference.我尝试了该命令的几种变体,并尝试了 escaping 并双重转义匹配字符串中的
$
和+
符号,但我所做的没有任何区别。 Can someone please offer a solution?有人可以提供解决方案吗?
I'm using Bash 3.2.57(1) and Perl 5.18.4 on macOS.我在 macOS 上使用 Bash 3.2.57(1) 和 Perl 5.18.4。
Try this perl command line with -0777
and \R
instead of \n
.试试这个 perl 命令行,使用
-0777
和\R
而不是\n
。 -0777
enabled slurp mode in perl to match across multiple lines and \R
lets it match all kind of line breaks (including DOS or OSX or Unix line breaks): -0777
在 perl 中启用 slurp 模式以匹配多行和\R
让它匹配所有类型的换行符(包括 DOS 或 OSX 或 Unix 换行符):
perl -0777 -i -pe 's/JAVA_OPTS="\$JAVA_OPTS -XX:\+UseParNewGC"\nJAVA_OPTS="\$JAVA_OPTS -XX:\+UseConcMarkSweepGC"/JAVA_OPTS="\$JAVA_OPTS -XX:+UseG1GC"/' file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.