Charlie Harvey

Vim macro: Sort aliases into alphabetical order with a macro

When I administer mail servers, I often use the aliases functionality to set up email groups and forwards. I find it very convenient to have everything in a single file. One thing that I don't like is keeping all the names in alphabetical order. While doing so might seeem like something from the twitterstream of , it is actually very convenient to have entries in order to help me find if emails are in an alias quickly.

What I needed was a Vim macro to automate away the tedious and error prone work of keeping entries in order. This is what I came up with. It may be useful for other Vimmers.

let @s = ':s/$/,/e^M:s/\s+//ge^M:s/([,:])/\1\r/eg^MkV?:^Mj:sort^MV/\n\n^M:s/\n//eg^MkJ:s/:/:\t\t/eg^M:s/,$//e^M'

And here it is in action …

Quick tip: use /e on substitution calls

As you can see the macro is mostly just a series of regex substitutions. An annoying but easily fixed problem with Vim’s macro handling is that if a substitution’s regex does not match, an error is thrown, causing the whole macro to fail. Yuk. You can avoid it by adding the /e flag to your substitutions.


Comments

  • Be respectful. You may want to read the comment guidelines before posting.
  • You can use Markdown syntax to format your comments. You can only use level 5 and 6 headings.
  • You can add class="your language" to code blocks to help highlight.js highlight them correctly.

Privacy note: This form will forward your IP address, user agent and referrer to the Akismet, StopForumSpam and Botscout spam filtering services. I don’t log these details. Those services will. I do log everything you type into the form. Full privacy statement.