2015-12-14 63 views
-6

我有一個Perl腳本,目前抓住包含單詞ACCOUNT的每一行。我怎樣才能在行首開始抓住包含單詞ACCOUNT的行?如何匹配以特定單詞開頭的行?

use strict; 

my $find = 'ACCOUNT'; 

open (NEW, ">", "output.txt") or die "could not open:$!"; 
open (FILE, "<", "Report.txt") or die "could not open:$!"; 

while (<FILE>) { 
    print NEW if (/$find/); 
} 

close (FILE); 
close (NEW); 
+0

僅僅在一開始,或者如果有空白,然後「ACCOUNT」,它可以嗎? – aschepler

+5

這並不難。我相信會有很多人排隊要求他們給出答案的十點,但是你怎麼做才能自己找到答案?谷歌是一個方便的工具 – Borodin

+2

我同意@Borodin。 [答案](http://perldoc.perl.org/perlre.html#Regular-Expressions)[out](http://www.regular-expressions.info/anchors.html),並不是很很難[找](https://regex101.com)。 –

回答

2

評論了空白版本,因爲人們似乎沒有閱讀評論。

use strict; 
my $find = 'ACCOUNT'; 

open (NEW, ">", "output.txt") or die "could not open:$!"; 
open (FILE, "<", "Report.txt") or die "could not open:$!"; 

while (<FILE>) { 
    # print NEW if $_ =~ /^\s*$find/ ; # Any line that starts with whitespace and followed by $find 
    print NEW if $_ =~ /^$find/ ; # Any line that starts strictly with $find 
} 
close (FILE); 
close (NEW); 
+0

這將使沒有任何主要空白的打印行加倍。 –

+1

我知道,我故意將兩個版本放在一起,以防他也想處理空白。正如您在代碼中放置的註釋中所見。 –

+1

非常感謝Ohad Dahan,這正是我所需要的。 – PhoenixJay

相關問題