useless has asked for the wisdom of the Perl Monks concerning the following question:

Hello all, I have google'd around and I am unable to find any code (perl) that will number all the lines in a txt document excluding blank lines. If you could help me out in any way at all I would extremely grateful,(please email me with your response) Kind regards Stephen Marron S00006531@itsligo.ie

Replies are listed 'Best First'.
Re: Line numbering
by borisz (Canon) on Oct 04, 2004 at 10:13 UTC
    perl -pe '$_ = "$.: $_"' your_file >your_new_file
    Update: I missed to skip the empty lines:
    perl -pe '$_ = /\S/ ? ++$q .": $_" : ""' in >out
    Boris
      As an alternative, you can decrement $. with no ill effects, apart from forgetting where you actually are. :)
      perl -pe '/\S/ ? s/^/$.: / : --$.'
Re: Line numbering
by Hena (Friar) on Oct 04, 2004 at 10:33 UTC
    Well, if using *nix try
    cat -n file
    With -b it numbers non-blank lines.
      And even that can be shortened to:
      nl file
      The -n and -b switches for cat are an example of creature feep.
Re: Line numbering
by pelagic (Priest) on Oct 04, 2004 at 10:15 UTC
    This solution excludes empty/whitespace lines:
    use strict; my $line_number = 0; while (<>) { chomp; next if (m/^\s*$/); ++$line_number; print $line_number, ': ', $_, "\n"; } ___INPUT___ These are all my lines for now. ___OUTPUT 1: These are 2: all 3: my lines 4: for 5: now.
    Share and enjoy!

    pelagic
Re: Line numbering
by Joost (Canon) on Oct 04, 2004 at 11:03 UTC