如何匹配以特定单词开头的行?
问题描述:
我有一个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);
答
评论了空白版本,因为人们似乎没有阅读评论。
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
仅仅在一开始,或者如果有空白,然后“ACCOUNT”,它可以吗? – aschepler
这并不难。我相信会有很多人排队要求他们给出答案的十点,但是你怎么做才能自己找到答案?谷歌是一个方便的工具 – Borodin
我同意@Borodin。 [答案](http://perldoc.perl.org/perlre.html#Regular-Expressions)[out](http://www.regular-expressions.info/anchors.html),并不是很很难[找](https://regex101.com)。 –