HOWTO remove empty lines with Regex

T

tor

Hi
I wan't to remove all empty lines in a file.
How can I do that with a regex:
s/<something>//;
What is this <something>

Torfinn
 
A

Anno Siegel

tor said:
Hi
I wan't to remove all empty lines in a file.
How can I do that with a regex:
s/<something>//;
What is this <something>

Apparently you want to remove empty lines not from a file, but a string.

There may be such a <something>, but it's easier with a different regex.

s/\n+/\n/g

does it.

tr/\n//s

does it faster.

Anno
 
G

Glenn Jackman

Tad McClellan said:
perl -n -i.old -e 'print unless /^\s+$/' file

Nitpick mode: remove empty lines too:
perl -n -i.old -e 'print unless /^\s*$/' file
^
^
 
T

tor

This might clearify
I got this file:
-----------------
Line 1<newlin>
Line 2<newlin>
<newlin>
Line 4<newlin>
----------------
I want this
-----------------
Line 1<newlin>
Line 2<newlin>
Line 4<newlin>
----------------

I want to remove the line who only contains <newline>,
so that the array @var only lines that contains data.

while(<FILE>) {
s/<something>/<nothing>/;
#Where <something> the regular expression I'm missing
push(@var,$_);
}
 
G

Gunnar Hjalmarsson

tor said:
This might clearify
I got this file:
-----------------
Line 1<newlin>
Line 2<newlin>
<newlin>
Line 4<newlin>
----------------
I want this
-----------------
Line 1<newlin>
Line 2<newlin>
Line 4<newlin>
----------------

I want to remove the line who only contains <newline>,
so that the array @var only lines that contains data.

while(<FILE>) {
s/<something>/<nothing>/;
#Where <something> the regular expression I'm missing
push(@var,$_);
}

In that case, you are on the wrong track with that s/// operator. You
can just do:

while (<FILE>) {
push @var, $_ unless $_ eq "\n";
}
 
J

Jeff 'japhy' Pinyan

Nitpick mode: remove empty lines too:
perl -n -i.old -e 'print unless /^\s*$/' file

But \n is matched by \s, and the $ anchor doesn't HAVE to match a newline,
so on a string like "\n", both /^\s+$/ and /^\s*$/ match.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,042
Latest member
icassiem

Latest Threads

Top