4

To replace all the occurrences of 'foo' in a text file with some other string, the usual Emacs command is M-x replace-string.

Off late, I have had to replace several such strings in my text files. Doing M-x replace-string for every expression I want to replace is tiring. Is there any Emacs command to 'batch replace' a bunch of strings with their alternatives?

This might look something like,

M-x batch-replace-strings RET foo1, foo2, foo3, RET bar1, bar2, bar3 RET where RET stands for hitting the return key.

So now foo1 has been replaced with bar1, foo2 with bar2 and foo3 with bar3.

1
  • 2
    The solution of this problem is applicable, provided the input is rearranged slightly as follows: M-x parallel-replace RET foo1 bar1 foo2 bar2 foo3 bar3 Commented Dec 30, 2011 at 20:27

1 Answer 1

6

This code does what you want, prompting for the string pairs pair-by-pair:

(defun batch-replace-strings (replacement-alist)
  "Prompt user for pairs of strings to search/replace, then do so in the current buffer"
  (interactive (list (batch-replace-strings-prompt)))
  (dolist (pair replacement-alist)
    (save-excursion
      (replace-string (car pair) (cdr pair)))))

(defun batch-replace-strings-prompt ()
  "prompt for string pairs and return as an association list"
  (let (from-string
        ret-alist)
    (while (not (string-equal "" (setq from-string (read-string "String to search (RET to stop): "))))
      (setq ret-alist
            (cons (cons from-string (read-string (format "Replace %s with: " from-string)))
                  ret-alist)))
    ret-alist))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.