Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^2: newlines in regular expressions

by sgifford (Prior)
on Dec 07, 2004 at 06:57 UTC ( #412845=note: print w/ replies, xml ) Need Help??


in reply to Re: newlines in regular expressions
in thread newlines in regular expressions

A few nits: The first answer requires that Perl read in slurp mode, and needs a g modifier to replace all occurences:

perl -p -e 'BEGIN { undef $/ } s/\n{2,}/\n/g'

Also, the two examples behave differently in the face of lines that contain only blank characters, like space and tab. The second will delete them, while the first will leave them intact. You can make the second leave them intact by using m/^$/; to make the first delete whitespace-only lines I think s/\n\s*\n/\n/g will work, but I haven't thought it through yet.


Comment on Re^2: newlines in regular expressions
Select or Download Code
Re^3: newlines in regular expressions
by eyepopslikeamosquito (Canon) on Dec 07, 2004 at 07:22 UTC
    perl -p -e 'BEGIN { undef $/ } s/\n{2,}/\n/g'

    Which can be shortened to:

    perl -p0777e 's/\n{2,}/\n/g'
    See perldoc perlrun for details of perl's -0 option.

Re^3: newlines in regular expressions
by tachyon (Chancellor) on Dec 07, 2004 at 11:59 UTC

    It is as you say.

Re^3: newlines in regular expressions
by tachyon (Chancellor) on Dec 07, 2004 at 12:09 UTC
    perl -pi -e 's/^\s*\z//' file.txt deals with blank lines with other whitespace.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://412845]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (21)
As of 2014-10-01 19:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (35 votes), past polls