如何在Perl中只写一个文件的某些行? [英] How can I write only certain lines of a file in Perl?
问题描述
我正在寻找一种方法来读取输入文件,并且只打印选择行到Perl中的输出文件。我要打印到输出文件的行都以 xxxx.xxxx.xxxx
开头,其中 x
是字母数字字符(句点是句点,而不是通配符)。这些线并不都具有相同的结束,如果这有区别。我想的像下面的( if
语句是所有的真正缺失,只要我能告诉)。
I am looking for a way to read an input file and print only select lines to an output file in Perl. The lines I want to print to the output file all begin with xxxx.xxxx.xxxx
, where x
is an alphanumeric character (the periods are periods, not wildcards). The lines do not all have the same ending, if that makes a difference. I'm thinking something like the following (the condition of the if
statement is all that is really missing as far as I can tell).
open(IN, "<$csvfile");
my @LINES = <IN>;
close(IN);
open(OUT, ">$csvnewfile");
print OUT @LINES if ([line starts with xxxx.xxxx.xxxx]);
close(OUT);
提前感谢!
推荐答案
这里是一个更好的方式循环通过你的线。它避免立即将您的整个输入文件加载到内存:
Here is a better way to loop through your lines. It avoids loading your whole input file into memory at once:
use strict;
use warnings;
open my $fhi, '<', $csvfile or die "Can not open file $csvfile: $!";
open my $fho, '>', $csvnewfile or die "Can not open file $csvnewfile: $!";
while (<$fhi>) {
print $fho $_ if m/^ \w{4} \. \w{4} \. \w{4} /x;
}
close $fho;
close $fhi;
请记住 \w
字符类还包括下划线。要避免下划线:
Keep in mind that the \w
character class also includes underscores. To avoid underscores:
print $fho $_ if m/^ [a-z\d]{4} \. [a-z\d]{4} \. [a-z\d]{4} /xi;
这篇关于如何在Perl中只写一个文件的某些行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!