Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

write exact lines of file

by b1rd (Novice)
on Oct 08, 2003 at 06:35 UTC ( #297492=perlquestion: print w/replies, xml ) Need Help??
b1rd has asked for the wisdom of the Perl Monks concerning the following question:


I have one newbie question.
I have text file and I would like to write content of this file e.g. from 4-th line to end of file, or from 5-th line to 10-th?


Replies are listed 'Best First'.
Re: write exact lines of file
by jmcnamara (Monsignor) on Oct 08, 2003 at 07:51 UTC

    Fouth line to end of file:
    perl -ne 'print if 4 .. eof' file

    Fifth line to tenth:

    perl -ne 'print if 5 .. 10' file

    Note, in the first example the eof if mainly a visual indicator. The following would work just as well:

    perl -ne 'print if 4 .. 1' file perl -ne 'print if 4 .. 0' file # or perl -ne 'print if $. >= 4' file


      From the very first perl golf tournament:

      perl -pe '11..exit'
      (11 for 10,6 for 5, etc)

      Attributable to many.

      And of course, this does the exact opposite of what the OP wanted! Teach me to read the question!

      edit: forgot -e switch, added caveat (thanks jmcnamara)
Re: write exact lines of file
by robartes (Priest) on Oct 08, 2003 at 06:58 UTC
    You can make use of the $. special variable:
    $ perl -ne 'print if ($. == 4)' test.txt Line 4 $ perl -ne 'print if ( 4 < $. and $. < 11)' test.txt Line 5 ... Line 10
    The $. stores the current line number of the last filehandle accessed: see here.


Re: write exact lines of file
by PodMaster (Abbot) on Oct 08, 2003 at 06:57 UTC
    That is indeed a newbie/fa-question (this is a good tutorial). If you look around, you may find it. One of the answers is to use Tie::File.

    MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
    I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
    ** The third rule of perl club is a statement of fact: pod is sexy.

      I wouldn't say that using Tie::File is a good advice for this particular problem. Tie::File is rather heavy-weight, in resource usage and time needed to learn its API. Tie::File pays back your investments by giving you some handy functionality, none of which you need for the problem at hand.

      It's like suggesting to use XS code to add two numbers. It's not impossible, it gives you lots of control and flexibility, but it doesn't make much sense.

      -n and $. are the solutions, not Tie::File.


      This way you can substitute a line i a text file by its number:
      use strict ; my $FILE = "file.txt"; open (FILE, "$FILE"); my @TOTAL = <FILE>; close FILE; $TOTAL[1] = "TEST\n"; my $FILE2 = "file2.txt"; open (FILE2, ">>$FILE2"); foreach (@TOTAL) { print FILE2 "$_"; } close FILE2;
Re: write exact lines of file
by punchcard_don (Beadle) on Oct 08, 2003 at 19:09 UTC
    Here's a method that's inelegant, but instructive and clear:

    1. Read the contents of your file into an array:

    open(FILE, filename); @LINES = <FILE>; close(FILE);

    Each array element now contains one line of the file.

    2. Now you can operate as you wish on the desired array elements to insert/change/delete desired new lines. For example, to change the nth line;

    $LINES[n] = 'some new text';

    or, to take the nth to pth lines of another file and replace the nth to pth lines of your original with them:

    open(FILE, filename1); @LINES = <FILE>; close(FILE); open(FILE2, filename2); @LINES2 = <FILE2>; close(FILE2); for $i (n .. p) { $LINES[$i] = $LINES2[$i]; }

    3. Re-write from the array to the file:

    open(FILE, filename); for $i (0 .. $#LINES) { print FILE "$LINES[$i]"; } close(FILE);
      No warnings, no strictures. Bad.

      use warnings; use strict;
      You should always, yes, always, check the results of system calls for errors.

      open(FILE, filename) or die "Cannot open filename:$!\n";

      There is absolutely no need in any of the examples to read the file into an array. It is faster and far less memory wasteful to loop through the file with while:

      while (<FILE>) { # do stuff }

      In your 3rd example, you are not opening the file for writing, so writing will fail. This would have been caught if you had allowed warnings.

      There are more problems, but since many posts above have dealt with this problem much better, I will cease now.

      Helgi Briem
      hbriem AT simnet DOT is

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://297492]
Approved by Corion
Front-paged by gmax
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2017-01-21 14:56 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (185 votes). Check out past polls.