Xah Lee, 2007-08, …, 2011-03-21
Suppose you need to rename a bunch of files by a string pattern, for all files in a directory. However, you do not want to rename all of them. You need to look at it in a case-by-case basis. What can you do?
Answer: emacs.
When in dired, call wdired-change-to-wdired-mode. Then, just edit the file names. When done, type【Ctrl+c Ctrl+c】 to commit the changes. 【Ctrl+c Esc】 to cancel the rename.
While you activated wdired, you can edit the file names by using any of emacs's Find & Replace commands. (e.g. query-replace.)
| Key | Command Name | Purpose |
|---|---|---|
| 【Ctrl+x Ctrl+q】 (emacs 23.1) | wdired-change-to-wdired-mode | Start rename by editing |
| 【Ctrl+c Ctrl+c】 | wdired-finish-edit | Commit changes |
| 【Ctrl+c Esc】 | wdired-abort-changes | Abort changes |
This feature is also listed under the menu 〖Immediate▸Edit File Names〗. This menu is available only when you are in dired.
While in wdired, you can edit the list of file names by emacs's find & replace commands. For example, call query-replace 【Alt+%】 or call query-replace-regexp 【Ctrl+Alt+%】. (See: Find & Replace with Emacs.)
There is a bug in emacs 22. (bug#394) If you rename 2 files by exchanging their names, one of the file will get deleted. For example, first file is named A and second is named B, and you rename them so that first is B and second is A. When you do commit, emacs will promp you that A already exsit and if you want to overwrite it. If you answer yes, then file A's content will be gone, and there will NOT be a file named A to be renamed B. In short, you lose a file. This is fixed in emacs 23, but i would be still careful if you rename many files that have existing names.
When renaming files to existing names, best to rename them to something else (such as adding a “x” in front), commit, and rename again.
A older method to rename files in batch is by the command dired-do-rename-regexp 【% R】.
Note: emacs's regex is not based on Perl's regex engine. For a summary and common patterns, see: Emacs Regex.