[Chicago-talk] Replacing consecutive newlines with a single newline

Andy_Bach at wiwb.uscourts.gov Andy_Bach at wiwb.uscourts.gov
Thu Sep 25 18:46:21 PDT 2008


>   I thought I knew it but after trying for almost one hour I am still
> unable to get it right.
  Your ideas much appreciated.

       perl -pe 's/(\n)+/\1/g' inputfile
       perl -pe 's/(\n)+/\1/sg' inputfile
>   are not working.

-p means read a line at at time, lines being text ending w/ "\n".  If you
want to eat the whole file, there's the 'slurpy' mode using the "dash zero"
command line switch
perl -0777 -pe 's/(\n)+/\1/g' unputfile

see perldoc perlrun:
-0[octal/hexadecimal]
specifies the input record separator ($/) as an octal or hexadecimal
number.
...
The special value 00 will cause Perl to slurp files in paragraph mode.  The
value 0777 will cause Perl to
slurp files whole because there is no legal byte with that value.

In theory:
perl -0777 -pe 's/\n+/\n/g' unputfile

would be faster/cheaper as you aren't asking to save the match (as you
already know what the replace is) but ...

a
-------------------
Andy Bach
Systems Mangler
Internet: andy_bach at wiwb.uscourts.gov
Voice: (608) 261-5738 Fax: 264-5932

It is easier to write an incorrect program than understand
a correct one.
Alan Perlis  http://www.cs.yale.edu/quotes.html



More information about the Chicago-talk mailing list