Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

(code) One-liner removes whitespace-only lines from text file

by ybiC (Prior)
on Dec 19, 2001 at 02:15 UTC ( #132953=snippet: print w/ replies, xml ) Need Help??

Description: Perl one-liner to remove from a text file all lines that contain only whitespace.

Other Ways To Do It (mostly not one-liners) can be found at the thread "How do I remove blank lines from text files?".

Hmmm... personally, I like Ovid's example below better than mine.   It *does* seem more directly recognizable.



perl -i.bak -ne 'print unless /^\s+$/' file.txt

Comment on (code) One-liner removes whitespace-only lines from text file
Download Code
Re: One-liner removes whitespace-only lines from text file
by FoxtrotUniform (Prior) on Dec 19, 2001 at 02:21 UTC

    This snippet removes all non-empty lines containing only whitespace, but I don't think that's particularly intuitive behaviour. If I want to remove all "blank" lines from a file, I probably want:

    perl -i.bak -ne 'print if /\S/' file.txt

    and if I want to get rid of all the lines with "useless" whitespace, I probably want to collapse them to empty lines:

    perl -i.bak -ne 's/^\s+$//;print' file.txt

    Update: Changed first one-liner to Ovid's for readability.

    --
    :wq
(Ovid) Re: One-liner removes whitespace-only lines from text file
by Ovid (Cardinal) on Dec 19, 2001 at 02:32 UTC
Re: One-liner removes whitespace-only lines from text file
by jmcnamara (Monsignor) on Dec 19, 2001 at 14:00 UTC

    This is attributable to abigail:      perl -lp00ee file

    Update: As chip points out, this one-liner removes blank lines and not whitespace-only lines.

    --
    John.

      Well, 10 out of 10 for cleverness, but abigail's trick only removes empty lines, i.e. those that match /^$/; but the original requirement was to remove lines made up of any combination of whitespace.

          -- Chip Salzenberg, Free-Floating Agent of Chaos

Back to Snippets Section

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (8)
As of 2015-07-04 14:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (60 votes), past polls