簡體   English   中英

如何grep在Perl中捕獲文件的多行模式

[英]How to grep capture a multiline pattern of a file in 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捕獲兩個字符之間的多行模式(在本例中為引號)?

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"

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

在命令行中:

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

這基本上就是您擁有的,但是0標志等效於代碼中的undef $/ 從手冊頁:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM