我想在Perl
中只使用Sed
来捕获给定文件中1000行和2000行之间的文件内容。 我尝试了下面,但它没有工作,请有人可以帮助我。使用perl提取给定行之间的文件内容
$firstLIne="1000";
$lastline="2000";
$output=`sed -n '$firstLIne,$lastline'p sample.txt`;
我想在Perl
中只使用Sed
来捕获给定文件中1000行和2000行之间的文件内容。 我尝试了下面,但它没有工作,请有人可以帮助我。使用perl提取给定行之间的文件内容
$firstLIne="1000";
$lastline="2000";
$output=`sed -n '$firstLIne,$lastline'p sample.txt`;
这里是另一个纯perl的溶液:
my ($firstline, $lastline) = (1000,2000);
open my $fh, '<', 'sample.txt' or die "$!";
while(<$fh>){
print if $. == $firstline .. $. == $lastline;
}
如果不使用变量其他地方,你可以使用special use case of ..
与常数(4 日款,如果你使用常量表达式,他们自动获得比$.
):
while(<$fh>){
print if 1000 .. 2000;
}
这里是重要的来自perldoc的部分为..
运算符:
在标量上下文中,“..”返回一个布尔值。运算符像双稳态触发器一样是双稳态的,并模拟sed,awk和各种编辑器的行范围(逗号)运算符。
编辑根据请求,将中间行存储在变量中。
my ($firstline, $lastline) = (1000,2000);
my $output = '';
open my $fh, '<', 'sample.txt' or die $!;
while(<$fh>){
$output .= $_ if $. == $firstline .. $. == $lastline;
}
print $ouput;
另外,如果你的文件不是太大(它完全适合到内存),你也可以阅读到一个列表,然后选择行你感兴趣:
my $output = join '', (<$fh>)[$firstline+1..$lastline]
为了比较,要做到这一点只在Perl中,一个可以写:
my $firstLine=1000;
my $lastLine=2000;
my $fn="sample.txt";
my $output;
open (my $fh, "<", $fn) or die "Could not open file '$fn': $!\n";
while (<$fh>) {
last if $. > $lastLine;
$output .= $_ if $. >= $firstLine;
}
close($fh);
注意,这将停止线$lastLine
之后,从文件中读取..因此,如果该文件包含100,000行它会只读第一2000行..
如果你只是想打印出来的线条则:
perl -ne 'print if 1000 .. 2000' example_data.txt
应该工作。
如果你想为并入到一个脚本,在某种程度上,你可以在“半啜食”的文件句柄:
use strict;
use warnings;
open my $filehandle, 'example_data.txt' or die $!;
my $lines_1k_to_2k ;
while (<$filehandle>) {
$lines_1k_to_2k .= $_ if 1000 .. 2000 ;
}
print $lines_1k_to_2k ;
的.=
运营商将线路添加到字符串变量$lines_1k_to_2k
仅if
他们在范围1000 .. 2000
很高兴了解Perl范围运算符.. – 2014-12-06 10:28:56
@Hâkon:我提供的链接是(几乎所有)运算符的perldoc页面。 '〜'二进制反转仅在优先表中提及。 ideom'=()=',虽然不是严格意义上的运算符,但有时候并没有被提及(如果你希望在列表上下文中有一些表达式求值,但只对结果的大小感兴趣,这很有用)。 – 2014-12-06 10:35:56
感谢您的解决方案..我可以将打印命令的结果写入perl变量。 – Reddy 2014-12-06 10:39:01