/var/log/mandarg

Mandar Gokhale's weblog on the internets

An Interesting Unix Puzzle

This post describes a rather intriguing Unix puzzle. What do you get when you run echo cat | sed statement? Clearly, the first part yields the string cat, but I don’t know sed well enough to get the answer off the cuff. Let’s see what does happen.

1
2
$ echo cat | sed statement
cement

Now that was a bit Unexpected. So somehow, the at part of cat is being replaced by ement from statement.

Now, due to the t’s, I noticed that this look very similar to:

1
s/at/ement

which looks pretty familiar! So maybe you can use arbitrary delimiters, and the ‘t’s are these?

Looking at the section of the sed info page Section 3.5 seems to confirm this:

3.5 The `s’ Command
===================

The syntax of the `s` (as in substitute) command is
`s/REGEXP/REPLACEMENT/FLAGS`. The `/` characters may be uniformly
replaced by any other single character within any given `s` command.

This, like a lot of other sed quirks, is news to me.

So, I suppose I was a bit wrong earlier – all of the ts are being used as delimiters instead of the usual /, and it’s just the a in cat that’s being replaced with an ement.

Our puzzle is thus equivalent to:

1
echo cat | sed 's/a/emen/'

..which, since it is a simple replace of a with emen, will give cement.

Just in order to make sure we have the right explanation, we can try using some random character, say #, as the delimiter.

1
2
$ echo cat | sed 's#a#emen#'
cement

Yep, it works!

❧ Suggestions, comments, etc. can be emailed to comments@mandarg.com