smilingbuddha
smilingbuddha

Reputation: 14660

Batch-replace a bunch of strings in a text file with Emacs

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.

Upvotes: 4

Views: 1286

Answers (1)

Trey Jackson
Trey Jackson

Reputation: 74440

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))

Upvotes: 6

Related Questions