2015-11-04 20 views
1

我有一個看起來是這樣的文件:如何用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捕獲兩個字符之間的多行模式(在這種情況下,它是引號)?

回答

2
my $str = do { local($/); <DATA> }; 
$str =~ /attribute3="([^"]*)"/; 
$str = $1; 
$str =~ s/\n/ /g; 

__DATA__ 
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" 
1

將整個文件讀入一個變量,並使用/attribute3=\"([^\"]*)\"/ms

+1

您不需要轉義雙引號,並且不需要'/ ms'修飾符。 –

+1

@glennjackman我向你保證,你沒有。我們不需要'.'來匹配換行符,因爲我們甚至沒有在這個模式中使用'.'。 [perlre](http://perldoc.perl.org/perlre.html#Modifiers) –

+0

@matt,很對。 –

1

在命令行:

perl -n0e '/\/attribute3="(.*)"/s && print $1' foo.txt 

這基本上是你有什麼,但0標誌是undef $/相當於在代碼中。從手冊頁:

-0 [八進制/十六進制]

指定輸入記錄分隔符($ /)爲一個八進制或十六進制數。如果沒有數字,則空字符是分隔符。