Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print specific lines from a file in Unix?

Tags:

unix

perl

I want to print certain lines from a text file in Unix. The line numbers to be printed are listed in another text file (one on each line).

Is there a quick way to do this with Perl or a shell script?

like image 272
itzy Avatar asked Dec 29 '22 09:12

itzy


1 Answers

Assuming the line numbers to be printed are sorted.

open my $fh, '<', 'line_numbers' or die $!;
my @ln = <$fh>;
open my $tx, '<', 'text_file' or die $!;
foreach my $ln (@ln) {
  my $line;
  do {
    $line = <$tx>;
  } until $. == $ln and defined $line;
  print $line if defined $line;
}
like image 84
Toto Avatar answered Jan 13 '23 13:01

Toto