我的文件中包含以下文本:
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.sqlshell变量的值未传递到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中处理特殊字符查找替换
发布评论