Tibor's Musings

Emacs Multifile Operations

The dired mode is an Emacs interface to the filesystem, enabling one to perform certain operations on multiple files. The dired mode can be combined with other Emacs goodies such as the search and replace tool into a powerful multi-file editing tool.

Dired Example One

Say we would like to rename all files named *.shtml.wml into *.php.wml in a certain directory such as /tmp. You may know of the Linux CLI tool mmv with which we could do:

$ mmv '*.shtml.wml' '#1.php.wml'

but what if we are on a system where mmv is not available? Shall we try to install it or write a little script to achieve what we want?

What about using Emacs's dired and its dired-do-rename-regexp command (bound on % R) instead. Firstly, press C-x d /tmp RET to launch dired on our working directory (or dired /tmp in the eshell). Then use this dired file regexp renaming command:

% R ^\(.*\)\.shtml\.wml$ RET \1.php.wml RET

and press y or n or ! to rename some or all of the matched files, and we are done.

Dired Example Two

We are moving away from javadoc-style of docstrings to epydoc-style of docstrings in our coding project, so we would like to replace all occurrences of @param foo bar by @param foo: bar recursively in all our sources.

Firstly, search for all the files containing @param something space, i.e. when the variable name not followed by a colon, and let us make a dired buffer out of these files, by means of find-grep-dired:

M-x find-grep-dired RET ~/src/cds-invenio/modules RET @param \(\w*\) SPC RET

Secondly, in the dired buffer, mark only the Python files for further processing:

% m \.py$ RET

Thirdly, replace wanted expressions in the preselected files:

Q @param \(\w+\) SPC RET @param \1: SPC RET

Now choose interactively y or n to replace or not the given occurrence of the param regexp, or use ! to replace silently every occurrence, etc.

Finally, save all buffers:

C-x s !

and we are done.

Another advantage of doing these replacements inside Emacs itself rather than via CLI one-liners is a much better interactivity: we can easily test our regexps, replace only some occurrences while not touching others, revert some of the edits back, etc.

emacs