I was given a directory of files in which I was asked to make some systematic changes. Because it was a one-off task, and because there were only a few hundred files I thought I'd use an Emacs keyboard macro.

My macro, in addition to making the desired changes, placed a bunch of ! in the buffer (since I was trying to answer a query about whether to replace an instance of pattern match with a declaration tell emacs to replace all instances, and if no instances were found it just inserted an !).

Is there a nice simple way of getting rid of all these ! using another keyboard macro and/or some simple elisp?

3 Answers 3


Unless you want an interactive confirmation, which you presumably don't since you're automatic the replacement of all occurrences, call replace-string or replace-regexp instead of query-replace-string or query-replace-regexp.

But you don't need a macro at all to perform the same replacement in several files. Open the directory containing the files in Dired (just use the normal way you open files, and select the directory). If there are several directories, you can use find-dired or one of its variants, or press i to insert a subdirectory. Mark the files where you want to perform the replacements: you can use m to mark the current file, or other commands such as % m to mark the files based on a regular expression for their name. Then press Q to perform a regexp replacement in all the files. This is interactive, but you can press Y to validate the replacement in all files.

man tr

Your entire task is a one-line bash command. I wouldn't bother using Emacs for it.

for f in * ; do mv $f tmp ; tr -d '!' < tmp > $f ; done

From your question, I'll assume you already can run a macro in all the files, if not, a handy trick is to create a list of files in one buffer, and create a macro that opens an item in the list and ends with the cursor at the next item. A simple search and replace removing ! would leave you with the same problem, since any file without ! would get one inserted.

A simple solution is to replace ! with !, which ensures that the character exists in every file, then run search and replace to remove it completely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.