36

How to rename from:

VAR1_1F_text.txt
VAR2_1F_text.txt
VAR3_2F_text.txt

to

1F_VAR1_text.txt
1F_VAR2_text.txt
2F_VAR3_text.txt

How to switch parts of filenames?

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160

3 Answers3

72

This can easily be done using dired:

  1. Enter a dired view of your directory

  2. Switch to writable dired mode (wdired-change-to-wdired-mode): C-xC-q

  3. Edit the file names listing as if it were a normal buffer (for example using a keyboard macro or a rectangular selection or query-replace). Here is a regexp-based solution:

    C-M-%\(VAR.\)_\(..\)RET\2_\1RET

  4. Finish editing (wdired-finish-edit): C-xC-s or C-cC-c

You're done!

François Févotte
  • 19,520
  • 4
  • 51
  • 74
  • 2
    You can also do it without WDired, just mark files you need with `m` (or `* s` to mark all files in buffer) and run `% R` to rename with regexp. – jafrog Jun 05 '13 at 12:03
  • The wdired method is a bit easier to work with b/c if you have something like `run-foo.sh`, `foo.conf` and `init-foo-script` and you wanted to replace foo with bar, it is simpler to just do a replace in the buffer than concoct a regex that matches the correct value and properly replaces it. That said, in the described scenario, % R does seem like it'd work just fine. – elarson Jun 29 '16 at 16:04
  • 3
    Is there nothing emacs can't do? – Scott Bale Dec 14 '16 at 20:07
  • How could I possibly have missed WDired for 20 years? Such a time saver! Thank you, @Francesco – Florent Georges Apr 12 '18 at 07:17
  • Just if anyone uses `spacemacs` you can enter the `wdired-change-to-wdired-mode` using ` b w` as in (buffer write) my `` is `space` for Evil mode. – Dr Neo May 19 '23 at 09:43
4

You could also use Magnar Sveen's multiple-cursors from here, github link.

Switch to writable dired, select the files you want to rename, M-x mc/edit-lines. This should create multiple cursor each with its own kill history.

Mehrad Mahmoudian
  • 3,466
  • 32
  • 36
ᐅdevrimbaris
  • 718
  • 9
  • 20
0

This technique, which I discovered on the internet, is highly beneficial. It enables you to perform various actions with emacs macros, including editing text files.

Basically what you see as text file save with C-x C-s.

Alt+x dired to go to the directory.
Alt+x dired-toggle-read-only 【Ctrl+x Ctrl+q】.
Then, just edit the file names. (You can use Alt+x query-replace or Alt+x query-replace-regexp [see Emacs: Find Replace in Current File] or rectangle commands. [see Emacs: Edit Column Text, Rectangle Commands])
When done, wdired-finish-edit 【Ctrl+c Ctrl+c】 to commit the changes.

To abort, Alt+x w dired-abort-changes 【Ctrl+c Ctrl+k】

Reference: http://xahlee.info/emacs/emacs/rename_file_pattern.html

itirazimvar
  • 859
  • 1
  • 10
  • 20