我有一個看起來是這樣的文件:如何用grep捕獲文件的多模式在Perl
Random words go here
/attribute1
/attribute2
/attribute3="all*the*things*I'm*interested*in*are*inside*here**
and*it*goes*into*the*next*line.*blah*blah*blah*foo*foo*foo*foo*
bar*bar*bar*bar*random*words*go*here*until*the*end*of*the*sente
nce.*I*think*we*have*enough*words"
我想用grep文件爲線\attribute3=
然後我要救找到字符串裏面的引號給一個單獨的變量。
這是我到目前爲止有:
#!/bin/perl
use warnings; use strict;
my $file = "data.txt";
open(my $fh, '<', $file) or die $!;
while (my $line = <$fh>) {
if ($line =~ /\/attribute3=/g){
print $line . "\n";
}
}
這是打印出來/attribute3="all*the*things*I'm*interested*in*are*inside*here**
但
我想all*the*things*I'm*interested*in*are*inside*here**and*it*goes*into*the*next*line.*blah*blah*blah*foo*foo*foo*foo*bar*bar*bar*bar*random*words*go*here*until*the*end*of*the*sentence.*I*think*we*have*enough*words
。
因此,我所做其次是:
#!/bin/perl
use warnings; use strict;
my $file = "data.txt";
open(my $fh, '<', $file) or die $!;
my $part_I_want;
while (my $line = <$fh>) {
if ($line =~ /\/attribute3=/g){
$line =~ /^/\attribute3=\"(.*?)/; # capture everything after the quotation mark
$part_I_want .= $1; # the capture group; save the stuff on line 1
# keep adding to the string until we reach the closing quotation marks
next (unless $line =~ /\"/){
$part_I_want .= $_;
}
}
}
上面的代碼不起作用。我如何grep捕獲兩個字符之間的多行模式(在這種情況下,它是引號)?
您不需要轉義雙引號,並且不需要'/ ms'修飾符。 –
@glennjackman我向你保證,你沒有。我們不需要'.'來匹配換行符,因爲我們甚至沒有在這個模式中使用'.'。 [perlre](http://perldoc.perl.org/perlre.html#Modifiers) –
@matt,很對。 –