Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: How to remove white space and more than a particular number of new lines!

by sundialsvc4 (Abbot)
on Apr 10, 2014 at 12:22 UTC ( #1081804=note: print w/ replies, xml ) Need Help??


in reply to How to remove white space and more than a particular number of new lines!

Without being a code-a-matic for you either, here’s a classic treatment of this sort of problem which can be done by Perl, or, perhaps even more simply, by awk:

There are two kinds of lines here:   those that are blank, and those that are not.   (A blank line would match something like /^\s*$/ ...)   If the line is not blank, then you want to output that line and set a counter of the number of blank-lines encountered to zero.   If it is, you want to increment that count, and output the line only if the count is so-far two or less.   You must initialize that counter to zero before the loop begins.   With this algorithm, a gap of one line would stand, but a gap of more than two lines would be two.

In data-processing in general, we all encounter a lot of “text-file problems” which can be reduced to the same basic idea:   what different types of lines might I encounter, how do I recognize them, and, having recognized them, what do I do with them.   (Also, what do I do at the beginning of the file and what do I do at the end.)   Well, the awk tool is specifically designed around that very idea, and the Perl programming language was originally birthed as an über-extension of awk ... both for good reasons.

Now, I’m sure that you can see your way to writing that very-short program based on this?


Comment on Re: How to remove white space and more than a particular number of new lines!
Re^2: How to remove white space and more than a particular number of new lines!
by Anonymous Monk on Apr 13, 2014 at 18:30 UTC
    I tried to capture whitespaces with /^\s*$/ but its not working. Can you pls show the correct way please
      Show us the actual code that you used when you "tried to capture whitespaces". Also tell us what "its not working" really means: what did it do, and how did that differ from what you wanted to do. These details will help us help you.

        i used this,

        $string =~ s/\t/ /g; $string =~ s/^\s*$//g;

        but the white spaced lines was not getting replaced.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2014-09-20 08:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (157 votes), past polls