Xah Lee, 2007-08, 2009-06
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.
Type “Alt+x dired”, mark your files, then type “%R” (or “Alt+x dired-do-rename-regexp”).
Start emacs by typing “emacs” in the command line interface prompt. (Or, double click the Emacs icon if you are in a Graphics User Interface environment)
First you need to select the files you want to rename. Use the graphical menu “File‣Open Directory”. Emacs will ask you for a directory path. Type the directory path, then press Enter.
Now, you will be shown the list of files, and now you need to “mark” the files you want to rename. You mark a file by moving the cursor to the file you want, then press m. Unmark it by pressing u. To mark all files by a regex, type “% m”, then give your pattern. For example, if you want to mark all jpg files, then type “% m jpg$”. To unmark all files, type U. To mark all files, type “U t”. (The “t” is a shortcut for toggle)
The “Mark” menu in dired mode.
Note that all the mark commands are also in the graphical menu.
Now type “Alt+x dired-do-rename-regexp”. Emacs will prompt you for the regex string and the replacement string.
Now, emacs will use your pattern and rename the marked files. Whenever it finds a match, it will stop and prompt you. If you want to make the change, type “y”. If you don't want to, type “n”. If you simply want emacs to go ahead and all renaming without asking, type “!”.
Note: emacs's regex is not based on Perl's regex engine. For a summary and common patterns, see: Emacs Regex.
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.
The command wdired-change-to-wdired-mode is under the dired menu “Immediate‣Edit File Names”.
Warning: There is a bug in emacs 22. 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. So, when you want to rename files to exiting names, just be careful. Best to rename them to something else, commit, and rename again.
Related essays: