[英]Passing a parameter to perl with -p
我有一个简短的Perl脚本,用于对文件运行正则表达式替换: perl -pi -e 's/x/y/' <file>
我想将参数传递给脚本,因此它将用命令行参数替换y (例如,类似perl -pi -e 's/x/$argv[1]/' <file>
但是当使用-pi参数时,我使用$ argv [1]不起作用。
I have never understood the preoccupation with one-line Perl programs, and I don't understand why you can't write a Perl script file to do this. 我从不了解单行Perl程序的问题,而且我也不明白为什么您不能编写Perl脚本文件来做到这一点。
However, you can remove an item from @ARGV
and save it in a variable before the -p
loop starts. 但是,您可以从
@ARGV
删除一个项目并将其保存在-p
循环开始之前的变量中。 Like this 像这样
perl -p -i -e 'BEGIN{ $r = pop } s/x/$r/' <file> <replacement>
Solution 1: Roll out your own loop. 解决方案1:展开自己的循环。
perl -i -e'$r = shift; while (<>) { s/x/$r/; print }' "$replacement" "$file"
Solution 2: Grab the var at compile time. 解决方案2:在编译时抓取var。
perl -i -pe'BEGIN { $r = shift; } s/x/$r/' "$replacement" "$file"
Solution 3: Use an env var instead of an argument 解决方案3:使用env var代替参数
R="$replacement" perl -i -pe's/x/$ENV{R}/' "$file"
perl -pi -e 's/x/y/' <file>
is equivalent to this: perl -pi -e 's/x/y/' <file>
等效于此:
while (<>) {
s/x/y/;
}
continue {
print or die "-p failed: $!\n";
}
This will pass every line of <file>
through the expression s/x/y/;
这将使
<file>
每一行都通过表达式s/x/y/;
and print the result. 并打印结果。 (Note the -i flag will modify
<file>
inplace). (请注意,-i标志将就地修改
<file>
)。 If you really need to pass in a replacement, why don't you list it directly in the substitution. 如果您确实需要传递替换项,为什么不直接在替换项中列出。 Either way it is still listed only once.
无论哪种方式,它仍然仅列出一次。
perl -pi -e 's/x/<replacement>/;' <file>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.