我有一个现有的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
之间的行?
答案 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_EDIT
或perlfaq5 - 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