November 17, 2023

awk Case Study - 9

Cliche generator, which creates new cliches out of old ones. The input is a set of sentences like

# cat cliche.txt
A rolling stone:gathers no moss.
History:repeats itself.
He who lives by the sword:shall die by the sword.
A jack of all trades:is master of none.
Nature:abhors a vacuum.
Every man:has a price.
All's well that:ends well.

where a colon separates subject from predicate. Our cliche program combines a random subject with a random predicate; with luck it produces the occasional mildly amusing aphorism:

A rolling stone repeats itself.
History abhors a vacuum.
Nature repeats itself.
All's well that gathers no moss.
He who lives by the sword has a price.

# cliche - generate an endless stream of cliches
# input: lines of form subject:predicate
# output: lines of random subject and random predicate


awk 'BEGIN { FS = ":" }
{ x[NR] = $1; y[NR] = $2 }
END { for (;;) print x[randint(NR)], y[randint(NR)] }
function randint(n) {
    return int(n *rand()) + 1 
}' cliche.txt

Don't forget that this program is intentionally an infinite loop. 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.