Using Emacs to recursively find and replace in text files not already open

  1. M-x find-name-dired: you will be prompted for a root directory and a filename pattern.
  2. Press t to "toggle mark" for all files found.
  3. Press Q for "Query-Replace in Files...": you will be prompted for query/substitution regexps.
  4. Proceed as with query-replace-regexp: SPACE to replace and move to next match, n to skip a match, etc.
  5. Press C-x s to save buffers. (You can then press y for yes, n for no, or ! for yes for all)

Projectile is really nice: C-c p r runs the command projectile-replace


  • 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

This answer is combined from this answer, from this site, and from my own notes. Using Emacs 23+.

Tags:

Emacs

Editor