繁体   English   中英

如何在Perl脚本中执行Perl One Liner

[英]How to execute Perl one liner inside Perl script

我想在Perl脚本中执行以下划线,以使一行与变量owner的值匹配,然后type并从文件中删除它:

perl -i -ne\"print unless /\b${owner}\b/ and /\b${type}\b/;\" /tmp/test

/tmp/test

node01    A    10.10.10.2
node02    A    10.20.30.1

当我在shell中执行时,这工作得很好,但是在Perl脚本中却不起作用。

我试图使用反引号, systemexec 似乎没有任何作用。

`perl -i -ne\"print unless /\b${owner}\b/ and /\b${type}\b/;\" /tmp/test`

system(q(perl -i -ne\"print unless /\b${owner}\b/ and /\b${type}\b/;\" /tmp/test));

是否可以在Perl脚本中执行Perl一个衬板?

如果是这样,我在这里做错了什么?

注意:我不需要使用sed,grep,awk等从文件中删除行的解决方案。

您不想从shell生成Perl代码,因此可以在shell中使用以下之一:

perl -i -ne'
   BEGIN { $owner = shift; $type = shift; }
   print unless /\b\Q$owner\E\b/ and /\b\Q$type\E\b/;
' "$owner" "$type" /tmp/test

要么

ARG_OWNER="$owner" ARG_TYPE="$type" perl -i -ne'
   print unless /\b\Q$ENV{ARG_OWNER}\E\b/ and /\b\Q$ENV{ARG_TYPE}\E\b/;
' /tmp/test

Perl的等效项是

system('perl',
   '-i',
   '-n',
   '-e' => '
      BEGIN { $owner = shift; $type = shift; }
      print unless /\b${owner}\b/ and /\b${type}\b/;
   ',
   $owner,
   $type,
   '/tmp/test',
);

local $ENV{ARG_OWNER} = $owner;
local $ENV{ARG_TYPE}  = $type;
system('perl',
   '-i',
   '-n',
   '-e' => 'print unless /\b\Q$ENV{ARG_OWNER}\E\b/ and /\b\Q$ENV{ARG_TYPE}\E\b/;',
   '/tmp/test',
);

您可以模拟-i-n标志,而不是单线调用。 -n只需要一个while循环。 -i涉及创建和写入临时文件,然后将其重命名为输入文件。

要选择临时文件名,可以使用/tmp/scriptname.$$ ,它将processId附加到您选择的基本名称之后。 更复杂的解决方案可以使用File :: Temp

open(IN, "<$file") || die "Could not open file $file";
open(OUT, ">$out") || die "Could not create temporary file $out";
while(<IN>) {
    print OUT $_ unless /\b$owner\b/ and /\b$type\b/;    
}
close(IN);
close(OUT) || die "Could not close temporary file $out";
rename($out, $file) || die "Failed to overwrite $file";

暂无
暂无

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

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