簡體   English   中英

perl 生銹。 如何讀取數據文件,然后在找到特定字符串時替換該文件中的整行

[英]Rusty in perl. How do I read in a datafile, and then replace an entire line within that file if a specific string is found

我需要一些快速的 perl 幫助。 這就是我想要的:

1) 從命令行運行我的 perl 腳本,並將數據文件作為參數傳入 2) 搜索傳入的數據文件,並查找字符串中第一次出現的單詞。 將字符串所在的整行替換為另一行文本。 3)將更新的文件保存到自身(在文件內替換)。

例如,這樣的事情:

./myPerlScript.pl data.txt

數據文件是這樣的:

_DATA__
path/to/some/file
path/to/some/other/file
path/to/SUBTSTRING/file #replace entire line if SUBSTRING is found
path/to/file

但實際的data.txt已更新(不寫入新文件)

與任何其他語言相同。

use Fcntl qw( SEEK_SET );

my $qfn = $ARGV[0];
open(my $fh, '+<', $qfn)
   or die("Can't open \"$qfn\": $!\n");

# Read contents of file into $file.    
my $file; { local $/; $file = <$fh>; }

if ($file =~ s/^.*SUBSTR.*/foo/mg) {
   seek($fh, 0, SEEK_SET)
      or die("seek: $!\n");
   truncate($fh, 0)
      or die("truncate: $!\n");
   print($fh $file)
      or die("print: $!\n");
   close($fh)
      or die("close: $!\n");
}

另一種方式:

  1. 在與原始文件相同的目錄中創建一個臨時文件。
  2. 從文件中讀取並將修改后的內容寫入新文件。
  3. 如果發生錯誤,請刪除臨時文件。
  4. 刪除原件。
  5. 重命名臨時。

在使用足夠新的 Perl 版本時執行以下操作會發生這種情況:

perl -nle'print /SUBSTR/ ? "foo" : $_' -i file

我們可以通過$^I訪問這個功能

$^I = '';
while (<>) {
   chomp;
   say /SUBSTR/ ? "foo" : $_;
}

這種方法有兩個優點:

  • 錯誤不會丟失數據。
  • 它允許我們逐行讀取文件(從而節省內存)。

還有三個缺點:

  • 原始文件和修改后的文件都需要足夠的磁盤空間。
  • 需要權限才能創建新文件。
  • 文件失去了它最初擁有的任何所有權和權限。

暫無
暫無

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

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