alonso@maxwell.mmwb.ucsf.edu (Darwin Alonso) (03/21/90)
How would one get perl to replace two or more successive blank lines with one blank line? Thanks, Darwin O.V. Alonso alonso@maxwell.mmwb.ucsf.edu U.C. San Francisco, or wk. (415) 476-8910; home 564-8601 alonso@cgl.ucsf.edu
jgreely@oz.cis.ohio-state.edu (J Greely) (03/21/90)
In article <13447@cgl.ucsf.EDU> alonso@maxwell.mmwb.ucsf.edu (Darwin Alonso) writes: >How would one get perl to replace two or more successive blank lines >with one blank line? Whole bunch of possibilities. Here's a relatively straightforward approach: while (<>) { if (/^$/) { $seen++; }else{ print "\n" if $seen; $seen = 0; print; } } print "\n" if $seen; A shorter solution that chews up more memory: undef $/; $_ = <>; s/\n{3,}/\n\n/g; s/^\n{2,}/\n/; print; I can't think of a better solution (shorter and more twisted, natch) at the moment, but I'm sure one of the other fertile minds out there can. -- J Greely (jgreely@cis.ohio-state.edu; osu-cis!jgreely)
tchrist@convex.COM (Tom Christiansen) (03/21/90)
In article <13447@cgl.ucsf.EDU> alonso@maxwell.mmwb.ucsf.edu (Darwin Alonso) writes: >How would one get perl to replace two or more successive blank lines >with one blank line? You can do this: #!/usr/bin/perl -n next if /^$/ && $skip++; print; $skip &= /^$/; Or as a one liner: perl -n -e 'next if /^$/ && $skip++; print; $skip &= /^$/;' Or you if you have lots of memory or little files: undef $/; $_ = <>; s/\n{3,}/\n\n/g; print; --tom -- Tom Christiansen {uunet,uiucdcs,sun}!convex!tchrist Convex Computer Corporation tchrist@convex.COM "EMACS belongs in <sys/errno.h>: Editor too big!"
merlyn@iwarp.intel.com (Randal Schwartz) (03/22/90)
In article <13447@cgl.ucsf.EDU>, alonso@maxwell (Darwin Alonso) writes: | How would one get perl to replace two or more successive blank lines | with one blank line? perl -ne 'print if /./ || !$s; $s = /^$/;' print "Just another Perl hacker,"; -- /=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\ | on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III | | merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn | \=Cute Quote: "Welcome to Portland, Oregon, home of the California Raisins!"=/
lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (03/22/90)
In article <13447@cgl.ucsf.EDU> alonso@maxwell.mmwb.ucsf.edu (Darwin Alonso) writes: : How would one get perl to replace two or more successive blank lines : with one blank line? Two primary ways. First is the slurp method: undef $/; $_ = <>; s/\n{3,}/\n\n/g; print; Second (and probably fastest) is the line-by-line method while (<>) { if ($_ eq "\n") { while (<>) { last unless $_ eq "\n"; } print "\n"; } print; } Alternately, there's while (<>) { next if "$prv$_" eq "\n\n"; $prv = $_; print; } There's also the grep method for Randal: print grep(($_ ne "\n" ? $_ : $prv eq "\n" ? '' : "\n", $prv = $_)[0], <>); Larry