Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

(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

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.

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.


      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?

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (11)
As of 2019-06-19 15:01 GMT
Find Nodes?
    Voting Booth?
    Is there a future for codeless software?

    Results (88 votes). Check out past polls.

    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!