http://qs1969.pair.com?node_id=132953

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