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

4
要替换文本文件中所有出现的“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。

2
只要将输入稍微重新排列如下,这个问题的解决方案就适用了:M-x parallel-replace RET foo1 bar1 foo2 bar2 foo3 bar3。 - huaiyuan
1个回答

6

这段代码可以实现你想要的功能,逐个对字符串对进行提示:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接