[英]how should I use system command in perl
我想用 $var 替換一行。 runnew 有
input= input/old/should/change;
replace= input/old/replace;
other = input/old/other;
replace_other= input/old/replace_other;
我的輸出文件應該是這樣的
input= input/old/should/New;
replace= input/old/New_replace;
other = input/old/New_other;
replace_other= input/old/New_replace_other;
我想用 input = input/old/should/New 替換“input =”; 我用過,
if ($#ARGV != 0) {
die "\n********USAGE <cellname> <tech>********\n";
}
$newinput=$ARGV[0];
open(my $fh, "$runnew") or die "Could not open rerun.txt: $!";
while (<$fh>) {
system ( sed -i "/input=.*/c\input= $newinput" $runnew );
}
但是彈出錯誤“Scalar found where operator expected at run.pl”及其顯示的 sed 行並詢問“(在 $runnew 之前缺少運算符?)。” 當我在終端上使用相同的 sed 時,它替換了 line 。
請問誰能指出錯誤在哪里?
是的,使用 Sed 很簡單,但我有不同行的文件,每一行都應該被替換。 如果您有比這更好的主意,請告訴我。 提前致謝。
system()
將字符串列表作為其參數。 您需要在傳遞給它的命令周圍加上引號。
system ( "sed -i '/input=.*/c\input= $newinput' $runnew" );
但是你的代碼看起來還是很奇怪。 您正在為輸入文件中的每一行運行完全相同的sed
命令。 那是你的意思嗎?
不太清楚你在這里想做什么。 但我相信最好的方法是不使用sed
並使用 Perl 進行轉換。
你為什么要調用sed
? 您的需求可以直接在 Perl 中更容易處理:
-i.bak
以啟用就地替換模式@ARGV
數組中刪除它,這樣它就不會被解釋為文件 Perl 會自動打開文件,寫入正確的文件並將舊文件重命名為.bak
。
#!/usr/bin/perl -i.bak
use warnings;
use strict;
my($replacement) = shift(@ARGV);
while (<>) {
s/input=.*/input= $replacement/;
print;
}
exit 0;
測試運行(對輸入數據進行有根據的猜測):
$ cat dummy1.txt.bak
input= test1
input= test2
$ cat dummy2.txt.bak
input= test3
input= test4
$ perl dummy.pl REPLACEMENT dummy1.txt dummy2.txt
$ cat dummy1.txt
input= REPLACEMENT
input= REPLACEMENT
$ cat dummy2.txt
input= REPLACEMENT
input= REPLACEMENT
或使用文件“rerun.txt”的內容:
$ perl dummy.pl REPLACEMENT $(cat rerun.txt)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.