2011-12-30 104 views
3

要用某些其他字符串替換文本文件中所有出現的'foo',通常的Emacs命令是M-x replace-string用Emacs批量替換文本文件中的一串字符串

關晚了,我不得不在我的文本文件中替換幾個這樣的字符串。爲我想要替換的每個表情做 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

[這個問題(的解決方案http://stackoverflow.com/questions/2588277/how-在同一時間內可以交換或替換多個字符串的代碼)是適用的,只要稍微重新排列輸入如下:Mx parallel-replace RET foo1 bar1 foo2 bar2 foo3 bar3 – huaiyuan 2011-12-30 20:27:07

回答

4

此代碼你想要做什麼,提示輸入字符串對對逐對:

(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)) 
相關問題