emacs rename files easily

Perm url with updates: http://xahlee.org/emacs/rename_file_pattern.html

Emacs: Rename Files Interactively by Pattern (regex; wdired)

Xah Lee, 2007-08, 2009-06, ..., 2010-09-12

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.

Summary

Type 【Alt+x dired】, then type 【Alt+x wdired-change-to-wdired-mode】. Then, just edit the file names. When done, type 【Ctrl+c Ctrl+c】 to commit the changes.

While in wdired, you can edit the list of file names by emacs's find/replace commands. For example, type 【Alt+5】for “query-replace” or 【Alt+%】 for “query-replace-regexp”.

A older, alternative method, but less convenient, is to call “dired-do-rename-regexp” 【% R】.

Detailed Explanation: Rename by Editing File Names

In emacs 22, there is a new way to rename a bunch of files, by simply editing the list of file names like normal text, then commit the change.

In dired, type 【Alt+x wdired-change-to-wdired-mode】. Then, just edit the file names in dired as if it's a normal text file. When you are done, type 【Ctrl+c Ctrl+c】 to commit the changes.

KeyCommand NamePurpose
Ctrl+x Ctrl+q】 (emacs 23.1)wdired-change-to-wdired-modeStart rename by editing
Ctrl+c Ctrl+cwdired-finish-editCommit change
Ctrl+c Escwdired-abort-changesAbort changes

This feature is also listed under the menu “Immediate‣Edit File Names”. This menu is available only when you are in dired.

Rename By Regex

While in wdired, you can edit the list of file names by emacs's find/replace commands. For example, type 【Alt+5】for “query-replace” or 【Alt+%】 for “query-replace-regexp”.

Warning: Renaming To Existing File Name

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. Best to rename them to something else (such as adding a “x” in front of name), commit, and rename again.

dired-do-rename-regexp

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.

Was this page useful? If so, please do donate $3, thank you donors!

Popular posts from this blog

11 Years of Writing About Emacs

does md5 creates more randomness?

Google Code shutting down, future of ErgoEmacs