如何在Perl Pie中处理特殊字符查找替换 [英] How to handle special characters in perl pie find replace

查看:93
本文介绍了如何在Perl Pie中处理特殊字符查找替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件中包含以下文本:

I have the following text in a file:

prompt **********************************************************************************
prompt **  Start
prompt **********************************************************************************
prompt **
prompt **  Calling:  FILE
prompt **
prompt **
@@FOLDER\FILE
prompt **
prompt **  commit
commit;
prompt **
prompt **
prompt **
prompt **********************************************************************************
prompt **  End
prompt **********************************************************************************

我这样做

$ perl -pi -e "s/FILE/$file/g" ./tmp.sql;

它将$ file中的所有内容替换为FILE单词的所有实例,但是当我调用

It replaces all instances of the word FILE with whatever I have in $file, but when I call

$ perl -pi -e "s/FOLDER/$folder/g" ./tmp.sql;

只有文件夹字符串,它会咳嗽,不替换任何东西,而我在其中调用它的外壳会吐出这些东西:

Which just has the folder string, it coughs up, doesn't replace anything and the shell where I am calling it from spits out this stuff:

Execution of -e aborted due to compilation errors.
Unquoted string "g" may clash with future reserved word at -e line 1.
Unknown regexp modifier "/R" at -e line 1, at end of line
Unknown regexp modifier "/F" at -e line 1, at end of line
Unknown regexp modifier "/5" at -e line 1, at end of line
Unknown regexp modifier "/4" at -e line 1, at end of line
Unknown regexp modifier "/7" at -e line 1, at end of line
Unknown regexp modifier "/5" at -e line 1, at end of line
Unknown regexp modifier "/6" at -e line 1, at end of line
Unknown regexp modifier "/_" at -e line 1, at end of line
Unknown regexp modifier "/2" at -e line 1, at end of line

任何人都知道给什么吗?

Anyone know what gives?

推荐答案

假设您有 folder =/some/path .在外壳处理完该行之后,对Perl的调用如下所示:

Suppose you have folder=/some/path. Here is what your call to Perl looks like after the shell is done processing the line:

perl -pi -e "s/FOLDER//some/path/g" ./tmp.sql

shell变量的值未传递到Perl;Shell在Perl看到字符串之前对字符串执行简单的文本扩展.

The value of a shell variable is not passed into Perl; the shell performs simple text expansion on the string before Perl ever sees it.

如果按字面意思进行替换,您将意识到需要输入类似的内容

If you were doing the replacement literally, you would realize you need to type something like

perl -pi -e "s/FOLDER/\/some\/path/g" ./tmp.sql

perl -pi -e "s|FOLDER|/some/path|g" ./tmp.sql

很难正确地转义 $ folder 中的值或猜测"一个安全的定界符.最安全的做法是将 $ folder 作为附加参数传递.

It is difficult either to properly escape the values in $folder or to "guess" a safe delimiter. The safest thing to do is to pass $folder as an extra argument.

perl -pi -e 'BEGIN {$replacement=shift}; s/FOLDER/$replacement/g' "$folder" ./tmp.sql

这篇关于如何在Perl Pie中处理特殊字符查找替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆