我正在尝试使用perl中的关键字搜索大文件,然后输出关键字出现的所有行,每行都换成新行。
答案 0 :(得分:4)
以下内容将打印包含keyword
到outputFile.txt
的所有行。输入文件作为参数传递给脚本。
<强> findkeyword.pl 强>
#!/usr/bin/perl
use strict;
use warnings;
open OUTPUT, ">outputFile.txt";
while (my $line = <>) {
if($line =~ m/keyword/){
print OUTPUT $line;
}
}
<强>输入强>:
./findkeyword.pl inputfile1 inputfile2 ...
编辑:正如@Kenosis在评论中所说,
使用词法范围的$ fh作为open(my $fh, ">", "outputFile.txt")
之类的文件句柄可能会更好。 参考:open()
如果您要将关键字存储在变量中,则可能需要先在其上调用 quotemeta
,或将其封在\Q...\E
中。