Tuesday, December 19, 2017

Bulk rename files in Emacs

Here's a problem I recently encountered at work which Emacs solved quite effectively with wdired-mode.

I had a large directory tree of Javascript files that I bulk-converted from coffeescript to ES6. The files originally had the extension ".js.coffee," but after conversion they all became ".js.js". Well, a ".js.js" file extension is absurd, right? How can I rename them all to a more sensible ".js"?

Easy -- use Dired mode to display the files, and then switch to 'wdired" (writeable-dired). String-replace the extension, save -- done and done.

But how to list all files from all subdirs in a single Dired buffer for string replacing? In Dired, subdirs can be "included" in the listing by typing 'i' when your cursor is on the subdir, but this is a pain for more than a couple of includes. After searching a bit, I cam across this bit in the Emacs docs for Dired:

The simplest way to include multiple directories in one Dired buffer is to specify the options ‘-lR’ for running ls. (If you give a numeric argument when you run Dired, then you can specify these options in the minibuffer.) That produces a recursive directory listing showing all subdirectories at all levels.

That is, "C-u 1 C-x d" to launch Dired, choose the parent dir, and then type "lR" in the minibuffer prompt for ls options. Voila! All the subdirs listed in your buffer. Now switch to wdired mode ("C-x q"), then query-replace the string ('M-%'). "C-c C-c" to save the buffer. Done.

I don't think there's an easier way to do a bulk rename.

No comments: