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 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

Elisp Commands Do thing-at-point

  1. Count Words
  2. Run Current File
  3. Delete Current File
  4. Copy File Path
  5. Convert Line Ending
  6. Make Backup
  7. Copy Column of Text to Clipboard
  8. Convert Image File
  9. Dired Rename Space to Hyphen
  10. Python 2to3 Wrapper
  11. Move Code to Files
  12. Update Web Feed
  13. Updating Page Tags
  14. Single Key Copy/Paste Register

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs

Emacs

Emacs Lisp

Misc