使用perl在给定行之间提取文件内容

时间:2014-12-06 09:07:36

标签: perl shell sed

我想在Sed中仅使用Perl来捕获给定文件中1000到2000行之间的文件内容。 我尝试了以下但是没有用,请有人帮我这个。

$firstLIne="1000";
$lastline="2000";

$output=`sed -n '$firstLIne,$lastline'p sample.txt`;

3 个答案:

答案 0 :(得分:4)

这是另一个纯粹的perl解决方案:

my ($firstline, $lastline) = (1000,2000);
open my $fh, '<', 'sample.txt' or die "$!";
while(<$fh>){
  print if $. == $firstline .. $. == $lastline;
}

如果你不在其他任何地方使用变量,你可以使用special use case of ..和常量(4 th 段如果使用常量表达式,它们会自动与{{}进行比较1}}):

$.

以下是while(<$fh>){ print if 1000 .. 2000; } 运算符的perldoc的重要部分:

  

在标量上下文中,&#34; ..&#34;返回一个布尔值。运算符是双稳态的,就像触发器一样,并模拟sed,awk和各种编辑器的行范围(逗号)运算符。

编辑每个请求,将中间行存储在变量中。

..

此外,如果您的文件不是太大(它完全适合内存),您也可以将其读入列表并选择您感兴趣的行:

my ($firstline, $lastline) = (1000,2000);
my $output = '';
open my $fh, '<', 'sample.txt' or die $!;
while(<$fh>){
  $output .= $_ if $. == $firstline .. $. == $lastline;
}

print $ouput;

答案 1 :(得分:3)

为了进行比较,要仅在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行..

答案 2 :(得分:1)

如果你只想打印出那些线条:

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

范围内