Friday, February 8, 2008

Golf

Now for some fun ;-). A friend asked me for a Vim macro this morning to strip all but the text contained with the double quotes of a file with the following format:

<option value="Automotive">Automotive</option>
<option value="Banking">Banking</option>
<option value="Biotech">Biotech</option>

etc...

After the macro it would be:

Automotive
Banking
Biotech
etc...

Initially, I came up with the following sequence (macro storage command omitted):

df"f"d$j0 (9 chars)

This works fine, but my OCD kicked in, and I decided to make it shorter:

df"f"D+ (7 chars)

For a brief moment, I thought this was as short as I could make it, but then...

df"wD+ (6 chars)

As far as I know, this is the shortest possible macro to accomplish this task, but I would love to be proven wrong.

UPDATE:

My friend Chris Sutter has contributed another solution using text objects that is pretty nifty.

di"Vp (5 chars)

or if you want to jump to next line as with the previous 6 char macro:

di"Vgp (6 chars)

Good stuff... thanks Chris!

3 comments:

Christopher Suter said...

:%s/^.*"\(.*\)".*$/\1/

a bit longer, but no macro repetition necessary

(sa)MAMMON said...

I don't like the shorter version you had (df"wD+ (6 chars)), becuase it uses w to go to the next word. If an entry had a non-word character, it wouldn't work. The f" was better in that regard.

However, the di"Vp is brilliant. I have never heard of text objects. Must investigate...

dominiko said...

How about:

df";D+