Cut to the chase

I got an email the other day about the code snippets I sometimes include in my posts. The direct answer to the emailer’s question was No, I don’t provide downloadable files, I expect you to copy and paste from the post. Often, though, this pasted code can’t be used immediately because it includes line numbers. I started putting in the line numbers a few months ago so I could more easily refer to parts of the code in the text of my posts. This advantage, I felt, outweighed the disadvantage of my readers not being able to use the code without a bit of editing.

In the post where I started using line numbers, I mentioned two ways to get rid of the line numbers after copying and pasting into a text editor:

  1. Searching for the regular expression /^ *\d+ / and replacing it with nothing. This will work in TextMate, BBEdit, vi, emacs, and probably a lot of other editors on the Macintosh that I have no experience with.
  2. Doing a column selection (Option-drag) in TextMate and deleting the first few columns.

This was not meant to be an exhaustive list--just a couple of methods that occurred to me as I was writing that post. I forgot about that venerable Unix command, cut. cut will extract everything except the line numbers by calling it like so:

cut -c 5-

The options tell cut to extract from column 5 through to the end of each line. For the code typically included in my posts, these are the correct options. The code that I give line numbers to usually uses two characters for the line numbers themselves followed by two spaces to separate the code. If I go crazy and include a chunk of code that runs for more than 100 lines, cut -c 6- would be the correct invocation.

cut gets the text from either standard input or a file. Because Apple has provided us with the (decidedly non-venerable) pbcopy and pbpaste commands for command-line interaction with the clipboard, we can set up a pipeline

pbcopy | cut -c 5- | pbpaste

that will take what’s on the clipboard, strip off the first four characters of every line, and put the result back on the clipboard. You can run this command within Terminal. The complete sequence would then be

  1. Select the line-numbered code and copy it onto the clipboard.
  2. Switch to Terminal and run pbcopy | cut -c 5- | pbpaste.
  3. Switch to your text editor and paste in the non-line-numbered code.
  4. Profit!

I feel certain there’s a way to avoid Terminal by using Quicksilver, but I haven’t figured it out yet.