简体   繁体   English

Perl搜索并替换不起作用

[英]Perl search and replace NOT working

I am trying to replace a string in a file but my procedure seems to be removing the string and not replacing it with what I want 我正在尝试替换文件中的字符串,但是我的程序似乎正在删除字符串,而不是用我想要的字符串替换

Example

perl -ne 'print unless s/ServerIp=${Solid.host}/ads/;' needsToBeReplaced.prp > blah.txt

will remove 将删除

"ServerIp=${Solid.host}" and just leave the line blank instead of printing "ads" in its place “ ServerIp = $ {Solid.host}”,只需将该行留空,而不是在其位置打印“ ads”

I am running in Windows by the way. 我正在Windows中运行。 Also I have no 3rd parameter in the regex because I only want to change the first occurrence. 另外我在正则表达式中没有第3个参数,因为我只想更改第一个参数。 I have also tried 我也尝试过

perl -pi -e 's/ServerPort=${Solid.port}/ads/;' needsToBeReplaced.txt 

but I get permission errors so editing in place is a no go 但出现权限错误,因此无法进行就地编辑

You print the line only if the substitution is not successful. 仅当替换不成功时才打印该行。 If you want to print always, do not use unless : 如果要始终打印,请不要使用, unless

perl -pe "s/ServerIp=\${Solid.host}/ads/;" needsToBeReplaced.prp > blah.txt

You should also escape the dollar sign to prevent its interpretation by Perl. 您还应该转义美元符号以防止Perl对其解释。

Also note that double quotes must be used on MS Windows. 另请注意,在MS Windows上必须使用双引号。

With what you've got now, if the substitute succeeds, it will return a true value, which means unless will be true, which means nothing will be printed. 现在,如果替换成功,它将返回一个true值,这意味着unless为true, unless将不会打印任何内容。 You could do it like this: 您可以这样做:

perl -ne 's/ServerIp=${Solid.host}/ads/; print;' needsToBeReplaced.prp > blah.txt

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

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