How to replace multiple lines of a newline with one with Perl regular expressions?

I have a document containing blank lines (\ n \ n). They can be removed with sed:

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

But how to do this with regular regular expression in perl? Everything that looks like the following simply does not show any result.

 echo $'a\n\nb'|perl -p -e 's/\n\n/\n/s' 
+6
regex perl
source share
3 answers

You need to use s/^\n\z// . The input is read line by line, so you will never get more than one new line. Instead, eliminate lines that do not contain any other characters. You must call perl with

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

No need for the /s switch.

+13
source share

The narrower problem of not printing blank lines is simpler:

 $(input) | perl -ne 'print if /\S/' 

prints all lines except those that contain only spaces.

+6
source share

Input is three separate lines, and perl with the -p option only processes one line.

The workaround is to tell perl split multiple lines of input at once. One way to do this:

 echo $'a\n\nb' | perl -pe 'BEGIN{$/=undef}; s/\n\n/\n/' 

Here $/ is a record separator variable that tells perl how to parse input in lines.

+4
source share

All Articles