← Back to Archives

Prefacing lines in emacs...

hacks

So, I wanted a way to insert the string PROMPT in front of every line in a region of a text file. (This is for an SQL script for Ray's DB Mgmt. class.).

Here's how to do it in emacs:

  1. Highlight the region that you want to preface each line of (hit Ctrl-spacebar and then arrow down or up to highlight).

  2. Hit M-x replace-regexp (on my mac, that's actually Ctrl-[ x replace-regexp).

  3. Enter the following regular expression (regexp, for short):

    ^(.*)$

    (the ^ is the marker for the beginning of the line, the \( and \) are escaped parentheses, the .* is regexp-speak for "any character, many or no times" and the $ is the marker for the end of the line.)

  4. Hit return.

  5. Now, what to replace it with? I chose

    PROMPT \1

    (PROMPT is what I wanted to preface each line with and \1 says to take the stuff found between the parentheses in the regexp and put it there.)

  6. Hit return.

For more on emacs replace-regexp type M-x describe-function replace-regexp.