Wandering Thoughts archives


Why I love Unix, number N (for some N)

Suppose that you want to find all two and three digit primes where all of the component digits are also prime (eg, 37 would qualify but 41 would not, since 4 is not prime).

Here is the simple Unix approach:

factor $(seq 10 999) | awk 'NF == 2 {print $2}' | egrep '^[12357]*$'

(I won't claim that this is obvious until you're immersed in the Unix pipe-bashing mindset, at which point it becomes all too easy to get sucked into the Turing tar pit.)

On a side note, seq is one of those programs that get more and more useful the more often I use it. It's not at all interesting on its own, but it really comes into its real power when used as an ingredient in shell script iteration.

And, oh yeah, it's a GNU tool. Another way that they've contributed to Unix in the Unix way.

(Okay, credit where credit is due; I believe that seq first showed up in Plan 9. But I will point out that the GNU tools people are the only people smart enough to reuse the idea.)

Update: Oops. As pointed out by a commentator, 1 is not a prime. This shows one drawback of these neat one-line things; they're so short and simple that you may be tempted to not double check your work. (This is especially embarrassing for me because I looked at the output of 'factor $(seq 1 9)' to make sure that I had the right set of single-digit primes, but discounted what factor printed for 1 without looking into it further.)

unix/UnixLove written at 01:29:24; Add Comment

Page tools: See As Normal.
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.