Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace multiple newlines with a single one with Perl's Regular Expressions?

Tags:

regex

perl

I've got a document containing empty lines (\n\n). They can be removed with sed:

echo $'a\n\nb'|sed -e '/^$/d'

But how do I do that with an ordinary regular expression in perl? Anything like the following just shows no result at all.

echo $'a\n\nb'|perl -p -e 's/\n\n/\n/s'
like image 658
Simon A. Eugster Avatar asked May 27 '10 19:05

Simon A. Eugster


1 Answers

You need to use s/^\n\z//. Input is read by line so you will never get more than one newline. Instead, eliminate lines that do not contain any other characters. You should invoke perl using

perl -ne 's/^\n\z//; print'

No need for the /s switch.

like image 182
Sinan Ünür Avatar answered Oct 11 '22 14:10

Sinan Ünür