Emacs: Rename File from Space to Hyphen/Underscore

By Xah Lee. Date: . Last updated: .

Here's a command that rename files by replacing space to underscore _ or hyphen -.

In dired, just press a key, then the file under cursor (or marked files) will be renamed with all space replaced to underscore.

(defun xah-dired-rename-space-to-underscore ()
  "In dired, rename current or marked files by replacing space to underscore _.
If not in `dired', do nothing.
URL `http://ergoemacs.org/emacs/elisp_dired_rename_space_to_underscore.html'
Version 2017-01-02"
  (interactive)
  (require 'dired-aux)
  (if (equal major-mode 'dired-mode)
      (progn
        (mapc (lambda (x)
                (when (string-match " " x )
                  (dired-rename-file x (replace-regexp-in-string " " "_" x) nil)))
              (dired-get-marked-files ))
        (revert-buffer))
    (user-error "Not in dired.")))
(defun xah-dired-rename-space-to-hyphen ()
  "In dired, rename current or marked files by replacing space to hyphen -.
If not in `dired', do nothing.
URL `http://ergoemacs.org/emacs/elisp_dired_rename_space_to_underscore.html'
Version 2016-12-22"
  (interactive)
  (require 'dired-aux)
  (if (equal major-mode 'dired-mode)
      (progn
        (mapc (lambda (x)
                (when (string-match " " x )
                  (dired-rename-file x (replace-regexp-in-string " " "_" x) nil)))
              (dired-get-marked-files ))
        (revert-buffer))
    (user-error "Not in dired")))

Give it a key. For example:

(progn
  (require 'dired )
  (define-key dired-mode-map (kbd "_") 'xah-dired-rename-space-to-underscore)
  (define-key dired-mode-map (kbd "-") 'xah-dired-rename-space-to-hyphen)
  ;; 
  )

see also Emacs: Cycle Replace Space Hyphen Underscore

Dired topics

  1. File Manager, dired
  2. Dired Customization
  3. Find Replace Text in Directory
  4. Batch Rename Files
  5. Dired Sort File by Time, Size
  6. Open File in External App
  7. Rename File from Space to Hyphen/Underscore
  8. Convert Image Files in Dired
Patreon me $5 patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

If you have a question, put $5 at patreon and message me.