Rename Files by a Text Pattern

Xah Lee, 2007-08

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

“Alt+x dired”, mark your files, then “Alt+x dired-do-rename-regexp”.

Detail

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)

emacs dired mark menu

above: 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.


Related essays:


Page created: 2007-08.
© 2007 by Xah Lee.
Xah Signet