簡體   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