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

Perl Masters:
Say I have a txt file like this:
blahblahblahblahblahblah blahblah blahblah blahblahblahblah blahblahbl +ahblahblahblah! blahblah blahblah blahblah blahblahblahblah. blahblahblahblahblah, blahblahblahblahblahblahblahblah blah blahblah blahblah blahblahblahblahblahblah; blahblahblahblah! blahblahblahblah, blahblahblahblah blahblahblahblah blahblahblahblah. +blahblahblahblah, blahblah.
How could I use powerful Perl to relace the three blank lines with spaces? and get something like this:
blahblahblahblahblahblah blahblah blahblah blahblahblahblah blahblahbl +ahblahblahblah! blahblah blahblah blahblah blahblahblahblah. blahblah +blahblahblah, blahblahblahblahblahblahblahblah blah blahblah blahblah + blah blahb lahblahblahblah; blahblahblahblah!blahblahblahblah, blahb +lahblahblah blahblahblahblah blahblahblahblah. blahblahblahblah, blah +blah.
I've tried something like s/\n/ /; and it did't work. Please enlighten me.... Thank you...

Replies are listed 'Best First'.
Re: delete blank lines in a txt file
by cLive ;-) (Prior) on Jul 20, 2001 at 21:01 UTC
    you need to make it a global replace, by adding a modifier, ie:
    s/\n//g;

    That's assuming you have the whole file in a string. If you have it in an array, use grep to do it:

    @array = grep /\S/, @array;

    Where \S represents a non space character - ie, only keep lines that contain non-space characters.

    cLive ;-)

Re: delete blank lines in a txt file
by larryk (Friar) on Jul 20, 2001 at 20:14 UTC
    one of the following from the command line should do the trick:
    perl -i.bak -ne "print if /./" filename
    or, to get rid of _all_ the newlines:
    perl -i.bak -ne "chomp, print if /./" filename

    "Argument is futile - you will be ignorralated!"

Re: delete blank lines in a txt file
by Wookie (Beadle) on Jul 20, 2001 at 20:22 UTC
    Assuming the blank lines are just carriage returns - the following should work:
    #!/usr/bin/perl -w use strict; open (IN,"blah.file")||die ("Failed to open file blah.file\n$!"); open (OUT,"blah.file.nospace")||die("Failed to open file blah.file.out + for writing\n$!"); my $count=0; while (<IN>) { chomp $_; if ($_=~m/^$/g) { $count++; } else { print OUT "$_\n"; } } close IN; close OUT; print 'Deleted '."$count".' blank lines'."\n"; exit (0);
    If you think you may have white spaces on your empty line - then you can change the line that reads:
    if ($_=~m/^$/g) {
    to read:
    if ($_=~m/^\s*$/g) {
    Hope this helps :)
    game(Wookie,opponent) eq 'Wookie' ? undef $problem : remove_limbs(arms,opponent);