要将文本文件中所有出现的'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。
答案 0 :(得分: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))