2011-03-01 67 views
0

我有以下文件:如何在自己的分隔符上分割文件?

some data 
some data 1 
some data 1 
hostname = abc 
some data 
some data 1 
some data 1 
some data 
some data 1 
some data 1 
hostname = xyz 
some data 
some data 1 
some data 1 
some data 
some data 1 
some data 1 
hostname = pqr 
some data 
some data 1 
some data 1 
some data 
some data 1 
some data 1 

我如何可以提取使用Perl 2名的主機名行條目之間的界限?

+0

我想這是一個罕見的情況之一時,你真的希望$ /可以設置爲一個正則表達式:-) – 2011-03-02 09:12:16

回答

0

啜食整個事情到一個字符串,$string,做這樣的事情:

$string =~ /hostname = abc\n(.*)hostname = xyz\n/s; 

abcxyz主機線之間的線路將在之後$1

0
perl -nle'/hostname = abc/../hostname = xyz/&&print' datafile 
+0

這隻會打印主機名的條目。 – Avinash 2011-03-01 19:13:54

+0

觸發器操作符的優先級低於&&。你可能想用'和'代替。 – 2011-03-01 19:26:17

+0

@Avinash:嘗試我的建議。如果我是對的,那麼'&& print'就會被放在右邊的檢查上。 – 2011-03-01 19:27:15

0

split確實夠用,只是給它正確的模式。

use DDS; Dump split /hostname = .*\n/, 'some data 
some data 1 
some data 1 
hostname = abc 
some data 
some data 1 
some data 1 
some data 
some data 1 
some data 1 
hostname = xyz 
some data 
some data 1 
some data 1 
some data 
some data 1 
some data 1 
hostname = pqr 
some data 
some data 1 
some data 1 
some data 
some data 1 
some data 1'; 

輸出

$VAR1 = "some data\nsome data 1\nsome data 1\n"; 
$VAR2 = "some data\nsome data 1\nsome data 1\nsome data\nsome data 1\nsome data 1\n"; 
$VAR3 = "some data\nsome data 1\nsome data 1\nsome data\nsome data 1\nsome data 1\n"; 
$VAR4 = "some data\nsome data 1\nsome data 1\nsome data\nsome data 1\nsome data 1"; 
1

如何:

#!perl -w 
my @someArray; 

while (<DATA>) { 
    if (/hostname.*/) { 
     print @someArray; 
     @someArray =(); 
    } 
    else { 
     push (@someArray, $_); 
    } 
} 

__DATA__ 
some data 
some data 1 
some data 1 
hostname = abc 
some data 
some data 1 
some data 1 
some data 
some data 1 
some data 1 
hostname = xyz 
some data 
some data 1 
some data 1 
相關問題