生疏的perl。我如何读取一个数据文件,然后在该文件中找到一个特定的字符串时,替换整行。

问题描述 投票:0回答:1

我需要一些快速的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 是更新的(不是写入新的文件)。

perl
1个回答
3
投票

和其他语言一样。

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" : $_;
}

这种方法有两个优点。

  • 出错时不会丢失数据
  • 它允许我们逐行读取文件(从而节省内存)。

还有三个缺点。

  • 需要足够的磁盘空间来存放原始文件和修改后的文件。
  • 需要创建新文件的权限。
  • 文件会失去原来的任何所有权和权限。
© www.soinside.com 2019 - 2024. All rights reserved.