Suppose I have a (potentially very large) text file that contains a word list with whitespace interjected. For example, it might look like this:
Cat Dog
Soup Rat
Cass Audrey
I want each word on a separate line (with no whitespace), like this:
Cat
Dog
Soup
Rat
Cass
Audrey
I can do a simple tr -d " "
to make that into:
CatDog
SoupRat
CassAudrey
(but that is not what I want).
I do not know what type of blank space separates those words, so assume that it's some combination of ordinary ASCII spaces and tabs. (We can assume that there are no invisible Unicode characters like em spaces and zero-width thingies.) Naturally, the words do not contain whitespace, so "à la", "alma mater", "apple pie", "at large" and "ice cream" are not valid words.
Assume that words may contain (non-blank) non-alphabetic characters, such as "AC/DC", "add-on", "AT&T", "audio-visual", "can't", "carbon-14", "jack-o'-lantern", "mother-in-law", "o'clock", "O'Reilly", "RS-232" and "3-D". Ideally the solution should tolerate non-ASCII characters, as in "Ångström", "Gödel", "naïve", "résumé" and "smörgåsbord".
How do I get rid of all those spaces while preserving (and isolating)
the indented words using common Unix/Linux tools like tr
, sed
or awk
?
It would be great if the solution would also work for more general cases of the stated problem; i.e., not just two-column text, but also random arrangements like:
Once upon
a midnight
dreary
while I pondered
weak and weary
Over many
a quaint and curious volume
of forgotten lore
set -f; printf ‘%s\n’ $(<file); set +f
. This is halfway a joke, because there are other types of expansion in the shell besides globs, but in some hackish cases it might be a very simple solution.