Reddy
Reddy

Reputation: 75

Extract file contents between given lines using perl

I want to use only Sed in Perl to capture the file contents between 1000 and 2000 lines in a given file. I tried the below but it didn't work,Can someone help me on this please.

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

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

Upvotes: 1

Views: 119

Answers (3)

G. Cito
G. Cito

Reputation: 6378

If you just want to print out the lines then:

perl -ne 'print if 1000 .. 2000' example_data.txt

should work.

If you want to incorporate that into a script somehow then you can "semi-slurp" the filehandle:

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 ;

The .= operator will add the lines to the string in variable $lines_1k_to_2k only if they are in the range 1000 .. 2000

Upvotes: 1

Patrick J. S.
Patrick J. S.

Reputation: 2935

Here is another pure perl solution:

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

if you don't use the variables anywhere else, you can use the special use case of .. with constants (4th paragraph if you use constant expression they automatically get compared to $.):

while(<$fh>){
  print if 1000 .. 2000;
}

Here is the important part from the perldoc for the .. operator:

In scalar context, ".." returns a boolean value. The operator is bistable, like a flip-flop, and emulates the line-range (comma) operator of sed, awk, and various editors.

Edit Per request, with storing the intermediate lines in a variable.

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

print $ouput;

Also, if your file isn't too big (it fits completely into memory) you also can read it into a list and select the lines you're interested in:

my $output = join '', (<$fh>)[$firstline+1..$lastline]

Upvotes: 4

H&#229;kon H&#230;gland
H&#229;kon H&#230;gland

Reputation: 40778

For comparison, to do this in Perl only, one could write:

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);

Note that this will stop reading from file after line $lastLine.. so if the file contains 100,000 lines it will only read the first 2000 lines..

Upvotes: 3

Related Questions