perl +插入文本

时间:2010-08-15 21:19:44

标签: perl

以下脚本text.pl(如下所述)定义在$ first_line和$ second_line之间追加$ insert文本 - myfile.txt

虽然:

$first_line=A 
$second_line=B
$insert = "hello world"

例如

在test.pl运行之前

A
B

运行test.pl后,我们得到:

A
hello world
B

问题:但是如果A行和B行之间有行间距,则它不会附加“hello world”如下所示,如果我还需要在脚本中更改以附加$ insert param在A到B之间的文件空间行?

A

B

test.pl脚本

use strict; 
use warnings; 

# Slurp file myfile.txt into a single string 
open(FILE,"myfile.txt") || die "Can't open file: $!"; 
undef $/; 
my $file = <FILE>; 

# Set strings to find and insert 
my $first_line = "A"; 
my $second_line = "B"; 
my $insert = "hello world"; 

# Insert our text 
$file =~ s/\Q$first_line\E\n\Q$second_line\E/$first_line\n$insert\n$second_line/; 

# Write output to output.txt 
open(OUTPUT,">output.txt") || die "Can't open file: $!"; 
print OUTPUT $file; 
close(OUTPUT); 

1 个答案:

答案 0 :(得分:2)

这将通过插入替换第1行和第2行之间的所有内容(甚至):

...

open my $in, '<', 'myfile.txt' or die "myfile.txt: $!";
my $content = do { undef $/; <$in> };
close $in;

# Set strings to find and insert 
my $first_line = quotemeta 'A'; 
my $second_line = quotemeta 'B'; 
my $insert = 'hello world'; 

# Insert our text 
$content =~ s/(?<=$first_line) .*? (?=$second_line)/\n$insert\n/xs; 

# Write output to output.txt 
open my $out, '>', 'output.txt' or die "output.txt: $!"; 
print $out $content; 
close $out;

...

修改/附录

阅读完"enhanced specification"后,如何解决这个问题会更加清晰。您将行的开始(^)和结束($)包括在正则表达式中。为了保持这种可维护性,我确实取出了表达式并制作了一个变量。我测试了它似乎工作(即使用'(')和东西):

...
# modified part

# Set strings to find and insert 
my $first_line = quotemeta ')'; 
my $second_line = quotemeta 'NIC Hr_Nic ('; 

# you won't need an array here, just write the lines down
my $insert =
'haattr -add RVG StorageRVG -string
haattr -add RVG StorageDG -string
haattr -add RVG StorageHostIds -string
haattr -delete RVG Primary
haattr -delete RVG SRL
haattr -delete RVG RLinks';

my $expr = qr{ (?<=^$first_line$)
               (\s+) 
               (?=^$second_line$)
            }xms;
# Insert our text 
$content =~ s/$expr/\n$insert\n/; 
...

我创建了这样一个文件:

stuff
stuff
)
NIC Hr_Nic (
stuff
stuff

并且插入正确。

此致

RBO