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. Emacs: File Manager, dired
  2. Emacs: Dired Customization
  3. Emacs: Find Replace Text in Directory
  4. Emacs: Batch Rename Files
  5. Emacs: Dired Sort File by Time, Size
  6. Emacs: Open File in External App
  7. Emacs: Rename File from Space to Hyphen/Underscore
  8. Emacs: Convert Image Files in Dired
Liket it? Put $5 at patreon. Or Buy Xah Emacs Tutorial. Thanks.