使用Emacs批量替换文本文件中的一串字符串

smi*_*dha 4 emacs

要用一些其他字符串替换文本文件中所有出现的'foo',通常使用Emacs命令M-x replace-string.

最近,我不得不在我的文本文件中替换几个这样的字符串.M-x replace-string 为我想要替换的每个表达做 一件事都很累人.是否有任何Emacs命令用他们的替代品"批量替换"一堆字符串?

这可能看起来像,

M-x batch-replace-strings RET foo1, foo2, foo3, RET bar1, bar2, bar3 RET 其中RET代表命中返回键.

所以现在foo1已被bar1替换,foo2替换为bar2,foo3替换为bar3.

Tre*_*son 5

此代码执行您想要的操作,逐个提示输入字符串对:

(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))
Run Code Online (Sandbox Code Playgroud)