如何在固定关键字之间用新文本替换文本?

时间:2014-09-11 16:37:52

标签: perl

我有一个现有的Perl脚本,它会像这样吐出文本:

set a = 4
set b = 5
set c = 0
set d = 3

现在我想修改此脚本以更新文本文件的内容。该文件看起来像这样:

...

// BEGIN

set a = 1
set b = 4
set c = 5

// END

...

如何使用现有Perl脚本生成的文本替换// BEGIN// END之间的行?

2 个答案:

答案 0 :(得分:1)

-用作第二个"文件"阅读STDIN

perl existing.pl | perl -pe'
  BEGIN{ local @ARGV=pop; @c =<> }
  $r = /BEGIN/ .. /END/;
  if ($r >1 and $r !~ /E0/) { $_ = ""; print @c if $r ==2 }
' file -

输出

...
...

// BEGIN
set a = 4
set b = 5
set c = 0
set d = 3
// END

..
..

答案 1 :(得分:0)

只需使用$INPLACE_EDITperlfaq5 - How do I change, delete, or insert a line in a file, or append to the beginning of a file?

中演示的任何其他方法即可
use strict;
use warnings;
use autodie;

my $file = 'file.txt';

# Your script generated data:
my $newdata = do { local $/; <DATA> };

# Insert new content
local @ARGV = $file;
local $^I   = '.bak';
while (<>) {
    if ( my $range = m{// BEGIN} .. m{// END} ) {
        print if $range == 1;
        print "$newdata$_" if $range =~ /E/;
    } else {
        print;
    }
}
unlink "$file$^I";    # Optionally delete backup

__DATA__
set a = 4
set b = 5
set c = 0
set d = 3