Thursday, June 11, 2009

Emacs Example Tutorial: replace words in a file

This example shows how to search-and-replace words in a file.

First we assume you are used to searching for strings or characters in a word, if you are not, please see this article on how to use emacs to find words and letters in a file.

You can replace strings or characters (words, letters) in a file in a manner very similar to find. You type this command (remember, M is the meta key, which is usually equal to holding down the alt key or tapping on the escape key):


    M %

So you can also think of this as:

    Alt Shift 5

After you type that key command sequence, Emacs will ask you:

    Query replace:

Then you type in the characters that you are looking for that you want to replace and hit enter. Then Emacs will ask you:

    Query replace [search-string-here] with:

Now you type in the characters you want to insert in place of the old word and again hit enter. Emacs will find the first instance of the "search" string (the word you want to replace), it will highlight that occurrence and then ask you:

    Query replacing [search-string-here] with [replacement-string-here]: (? for help)

If you want that occurrence to be replaced, you just tap the y key for "yes". Emacs will automatically move on to the next occurrence of the string you searched for and ask again:

    Query replacing [search-string-here] with [replacement-string-here]: (? for help)

If you want to skip any particular occurrence, just tap the n key for "no". Emacs will continue find and replace until you reach the bottom of the file.

No comments: