Emacs: Rename File, Space to Hyphen/Lowline 🚀

By Xah Lee. Date: . Last updated: .

Here's a command that rename files by replacing space to low line _ 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 lowline _.
If not in `dired', do nothing.

URL `http://xahlee.info/emacs/emacs/elisp_dired_rename_space_to_underscore.html'
Version 2016-10-04 2020-03-03"
  (interactive)
  (require 'dired-aux)
  (if (eq major-mode 'dired-mode)
      (let ((markedFiles (dired-get-marked-files )))
        (mapc (lambda (x)
                (when (string-match " " x )
                  (dired-rename-file x (replace-regexp-in-string " " "_" x) nil)))
              markedFiles)
        ;; (dired-next-line 1)
        (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://xahlee.info/emacs/emacs/elisp_dired_rename_space_to_underscore.html'
Version 2016-10-04 2019-11-24"
  (interactive)
  (require 'dired-aux)
  (if (eq 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 Space Hyphen Underscore

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Xah Emacs Commands