Some Editor Tricks

Here's the scenario (fictional, but not too far removed from real life): I want to munge some data I have into code. Let's say I have this in my editor:

The Comedy of Errors
Much Ado About Nothing
Twelfth Night

and the result I want is this:

THE_COMEDY_OF_ERRORS = "The Comedy of Errors"
MUCH_ADO_ABOUT_NOTHING = "Much Ado About Nothing"
TWELFTH_NIGHT = "Twelfth Night"

My editor of choice is vim and I like to run in a Unix (these days that usually means Linux) environment. Given those tools, here's one way to do it.

In command mode, I type 3yy (yank three lines), move the cursor to the line where I want to put them and hit p (for put).

The Comedy of Errors
Much Ado About Nothing
Twelfth Night

The Comedy of Errors
Much Ado About Nothing
Twelfth Night

I use the bang command to pipe the first three lines through sed 's/ /_/g'. (To pipe three lines through a shell command, type 3!! in command mode, then type the command at the colon prompt at the bottom of the screen.) This sed command replaces all spaces with underscores, leaving:

The_Comedy_of_Errors
Much_Ado_About_Nothing
Twelfth_Night

The Comedy of Errors
Much Ado About Nothing
Twelfth Night

I pipe the first three lines through perl -pe 's/\w+/uc($&)/e'. This forces all letters to uppercase, leaving:

THE_COMEDY_OF_ERRORS
MUCH_ADO_ABOUT_NOTHING
TWELFTH_NIGHT

The Comedy of Errors
Much Ado About Nothing
Twelfth Night

I pipe the last three lines through awk '{ print " = \"" $0 "\""}'. This inserts an equals sign and surrounds the original lines with (simple) double quotes.

THE_COMEDY_OF_ERRORS
MUCH_ADO_ABOUT_NOTHING
TWELFTH_NIGHT

 = "The Comedy of Errors"
 = "Much Ado About Nothing"
 = "Twelfth Night"

At this point, it's a simple process to move the lines to their correct places using a combination of dd (delete line) and p (put line) and J (join lines) to get my desired result.

Things that really help when using this kind of approach:

  • an open shell window nearby to try one-liners on test data
  • trustworthy multiple levels of undo/redo
  • lots of practice with editor basics