Deblank
June 28, 2019
Today’s task is easy. I expect to see lots of imaginative and over-the-top solutions:
Write a program that passes its input to its output, removing any lines that are either empty or contain only “white” characters like space and tab.
Your task is to write a program that removes blank lines from files. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Python 3:
As a pseudo-one-liner in Python, abusing list comprehension syntax:
import sys; [sys.stdout.write(line) for line in sys.stdin if line.strip()]
Rust version:
Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=930b30b55bac3d1783827bd1cd70f06b
gawk /\S/
There’s supposed to be two backslashes in front of the “S” in that gawk expression. Looks like the text-entry form here stripped one of them.
Here’s a solution with a vim command:
Intriguing problem, with a practical aspect to it! Here is my approach to it, using Julia:
function ContainsOnlyWhiteCharacters(text::AbstractString)
wc = [‘ ‘, ‘\t’, ‘\n’] # white characters
end
function process(fn::AbstractString)
f = open(fn)
lines = readlines(f)
close(f)
n = length(lines)
ind = BitArray(undef, n)
end
Cheers
An unimaginative, under-the-top Haskell version. The octal escapes in the printf produce a Unicode thin space.
#lang racket
(require 2htdp/image)
(let ((white (car (image->color-list (text " " 12 "black")))))
(for ([line (port->lines)])
(unless
(for/and ([pixel (image->color-list (text line 12 "black"))])
(equal? pixel white))
(displayln line))))