Home: Perl Programming Help: Intermediate:
sed fetch line

New User

Nov 1, 2017, 10:39 AM

Views: 5251
sed fetch line

Hi everybody,
I am trying to get a line from the line number of a file.
Do i have to use something like :
my $line = `sed ${number}q $file`
Thank you for your help.

Veteran / Moderator

Nov 1, 2017, 11:42 AM

Views: 5246
Re: [gaetan3009] sed fetch line

No reason to fork another process by going out to the shell to run a sed command. Perl has several ways to get a line on a specific line number.

This is probably how I'd do it.

use strict; 
use warnings;
use autodie;

my $file = 'somefile.txt';
open my $fh, '<', $file;

my $line;
while ($line = <$fh>) { close $fh and last if $. == 4 }

print $line;

(This post was edited by FishMonger on Nov 1, 2017, 11:43 AM)