簡體   English   中英

在Perl中搜索並替換文件?

[英]Search and replace in file in Perl?

從此示例開始 ,接着是另一個SO問題。

我在基本的perl腳本中添加了以下代碼。

#!/usr/bin/perl

$^I = '.bak'; # create a backup copy 

while (<>) 
{
   s/NewProdId/$ARGV[1]/g; # do the replacement
   s/PortId/$ARGV[2]/g; # do the replacement
   s/AssemblyId/$ARGV[3]/g; # do the replacement
   print; # print to the modified file
}

但是,當我用一個以上的參數調用perl腳本時,它就會中斷。 看來我誤以為其他參數打開了文件名。

無法打開1-THU-71:./process.pl第11行,<>行37中沒有此類文件或目錄。

無法打開1-5XJ0DF:./process.pl第11行,<>行37中沒有此類文件或目錄。

無法打開1-3F0MB9:./process.pl第11行,<>第37行中沒有此類文件或目錄。

我的bash腳本調用是這樣的:

./process.pl "test.txt" $values

我在這里做錯了什么?

菱形運算符<>嘗試打開參數中提到的所有文件。 您應該從@ARGV中刪除不是文件名的元素:

my @ar = @ARGV;
@ARGV = shift @ARGV;

while (<>) 
{
   s/NewProdId/$ar[1]/g; # do the replacement
   s/PortId/$ar[2]/g; # do the replacement
   s/AssemblyId/$ar[3]/g; # do the replacement
   print; # print to the modified file
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM