作为这个问题的后续,它试图找出如何做这样的事情,这应该很容易,这尤其阻止我更习惯于使用Emacs,而是启动我已经熟悉的编辑器。在编辑多个文件时,我经常使用这个示例。

在Ultraedit中,我用Alt+s然后p来显示一个带有选项的对话框:查找(包括跨多行使用正则表达式),替换,在文件/类型中,目录,匹配大小写,仅匹配整个单词,列出更改的文件和搜索子目录。通常我会先用鼠标点击-拖动选择我想要替换的文本。

只使用Emacs本身(在Windows XP上),不调用任何外部实用程序,如何替换所有的foo\nbar与bar\nbaz在*.c和*.h文件中的一些文件夹和它下面的所有文件夹。也许Emacs并不是最好的工具,但是如何用最少的命令就能轻松完成呢?


当前回答

它不是Emacs,但xxdiff附带了一个名为xx-rename的工具,该工具可以一次对多个字符串执行此操作(例如From To From To From To From To),并带有交互式提示,保存所有修改文件的备份,并生成一个简短的上下文更改日志。这是我在进行大型/全局重命名时倾向于使用的方法。

其他回答

M-x find-name-dired RET it may take some time for all the files to appear in the list, scroll to bottom (M->) until "find finished" appears to make sure they all have loaded Press t to "toggle mark" for all files found Press Q for "Query-Replace in Files...": you will be prompted for query/substitution regexps. Proceed as with query-replace-regexp: SPACE or y to replace and move to next match, n to skip a match, etc. Type ! to replace all occurrences in current file without asking, N to skip all possible replacement for rest of the current file. (N is emacs 23+ only) To do the replacement on all files without further asking, type Y. Call “ibuffer” (C-x C-b if bound to ibuffer, or M-x ibuffer RET) to list all opened files. Type * u to mark all unsaved files, type S to save all marked files * * RET to unmark all marks, or type D to close all marked files

这个答案结合了这个答案、这个网站和我自己的笔记。使用Emacs 23+。

对于这个任务,使用dred来递归到一个深目录树将会有点慢。您可以考虑使用标记-查询-替换。这确实意味着要花费一些钱来创建一个标签表,但这通常是有用的,而且是快速的。

对于打开的缓冲区,这是我所做的:

(defun px-query-replace-in-open-buffers (arg1 arg2)
  "query-replace in all open files"
  (interactive "sRegexp:\nsReplace with:")
  (mapcar
   (lambda (x)
     (find-file x)
     (save-excursion
       (goto-char (point-min))
       (query-replace-regexp arg1 arg2)))
   (delq
    nil
    (mapcar
     (lambda (x)
       (buffer-file-name x))
     (buffer-list)))))

我想推荐一个还没有被提及的伟大工具,即Helm。

它是许多标准Emacs操作的一个很好的替代品,包括补全、搜索等。特别是,helm-find-files允许在多个选定文件中执行查询替换(包括regexp)。

只需打开helm-find-files,用M-SPC标记相关文件,然后使用F6或F7在所选文件中运行query replace或query replace regexp。

M-X Dired, t标记所有文件,Q查询替换所有文件中的文本。 在执行query-replace命令之前,可以使用i命令展开子目录。 我添加的关键信息是,如果你给I命令加一个前缀(control-u), 它会提示你输入arg,而-R参数会递归展开所有子dirs 进入干燥的缓冲器。所以现在您可以查询搜索整个目录中的每个文件。