How to write from the nth line to a file using perl

I have the source text in the file and search for the code that will take the second (or nth - in general) line from this file and print to a separate file.

Any idea how to do this?

+1
source share
5 answers

You can do this natively in Perl with a flip-flop operator and a special variable $.(used internally ..) that contains the current line number:

# prints lines 3 to 8 inclusive from stdin:
while (<>)
{
    print if 3 .. 8;
}

Or from the command line:

perl -wne'print if 3 .. 8' < filename.txt >> output.txt

You can also do this without Perl with: head -n3 filename.txt | tail -n1 >> output.txt

+5
source

You can always:

  • Read the entire file, but it is in one variable.
  • Separate the variable on a new line and store it in an array
  • 1 ( ) n-1
0

script.pl > outfile ( → outfile )

3 arg open, 2 arg open.

#!/usr/bin/perl
use strict;
use warnings;
use English qw( -no_match_vars );
use Carp qw( croak );

my ( $fn, $line_num ) = @ARGV;

open ( my $in_fh, '<', "$fn" ) or croak "Can't open '$fn': $OS_ERROR";

while ( my $line  = <$in_fh> ) {
    if ( $INPUT_LINE_NUMBER == $line_num ) {
        print "$line";
    }
}

note: $INPUT_LINE_NUMBER == $.

, .

script.pl <infile> <outfile> <num1> <num2> <num3> ...

#!/usr/bin/perl
use strict;
use warnings;
use English qw( -no_match_vars );
use Carp qw( croak );
use List::MoreUtils qw( any );

my ( $ifn, $ofn, @line_nums ) = @ARGV;

open ( my $in_fh , '<', "$ifn" ) or croak "can't open '$ifn': $OS_ERROR";
open ( my $out_fh, '>', "$ofn" ) or croak "can't open '$ofn': $OS_ERROR";

while ( my $line  = <$in_fh> ) {
    if ( any { $INPUT_LINE_NUMBER eq $_ } @line_nums ) {
        print { $out_fh } "$line";
    }
}
0

, , :

line_transfer_script.pl:

open(READFILE, "<file_to_read_from.txt");
open(WRITEFILE, ">File_to_write_to.txt");

my $line_to_print = $ARGV[0]; // you can set this to whatever you want, just pass the line you want transferred in as the first argument to the script
my $current_line_counter = 0;

while( my $current_line = <READFILE> ) {
  if( $current_line_counter == $line_to_print ) {
     print WRITEFILE $current_line;
  }

  $current_line_counter++;
}

close(WRITEFILE);
close(READFILE);

: perl line_transfer_script.pl 2, file_to_read_from.txt _to_write_to.txt.

-1
my $content = `tail -n +$line $input`;

open OUTPUT, ">$output" or die $!;
print OUTPUT $content;
close OUTPUT;
-1

Source: https://habr.com/ru/post/1757191/


All Articles