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

November 25, 2009

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.)

Comments on this page:

From at 2009-11-25 03:56:57:

Technically, 1 isn't a prime number.... :)

By cks at 2009-11-25 08:58:55:

This is what I get for not checking my vague memories. Well, fortunately the change to make this correct is easy.

By Dan.Astoorian at 2009-11-25 10:18:08:

I believe that seq first showed up in Plan 9.

But the idea is much older than that. "jot" first appeared in 4.2BSD; I've always wished more Unix/Linux distributions had included it.


From at 2009-11-25 15:08:04:

I thought 'seq' was first mentioned in Kernighan & Pike's "The UNIX Programming Environment", don't have a copy handy to confirm, though ...

From at 2009-11-25 20:27:47:

As a further aside on seq I rarely find myself using it now recent versions of bash support the {1..10} expansion (which also works in reverse, i.e. {10..1}, which seq doesn't handle as succinctly).

(Although actually zsh's version is even better, e.g. {02..15} pads without needing to think about the -w option).

Written on 25 November 2009.
« An important lesson for me on Fedora upgrades
Some notes for myself on git bisect »

Page tools: View Source, View Normal, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Wed Nov 25 01:29:24 2009
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.