Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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

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

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

Replies are listed 'Best First'.
(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 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
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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2024-03-29 12:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found