I want to make some clean-up with auto-generated files. How can I delete all the files matching some regexp mask from within elisp? As an example of desired functionality... Something like the line below:

(delete-file "*.txt")

should delete all the text files in the current working directory...


3 Answers 3

(dolist (filename (directory-files "working-dir"))
  (when (string-match-p "\\.txt\\'" filename)
    (delete-file (file-name-concat "working-dir" filename))))
  • Or use dired? Commented Jun 19, 2023 at 17:15
  • @FranBurstall: I'm not familiar with dired. Maybe you can write an answer that uses dired, if you're familiar with it.
    – shynur
    Commented Jun 19, 2023 at 17:55
  • 2
    You can use a match argument in directory-files and avoid the explicit string-match.
    – NickD
    Commented Jun 19, 2023 at 18:28

Using dired as @FranBurstall suggested in a comment: use C-x C-f (find-file) on the directory, mark files for deletion with % d (dired-flag-files) followed by some regexp (e.g. .*\.txt$ - note that this is a regexp, not a glob and it specifies files whose names end with .txt), then after looking to make sure that you've got all the files you want and only those, press x to execute the deletions. Otherwise, press U to unmark everything and try again.


Here is a slightly improved version of shynur's snippet, that covers my needs. I've included NickD's comment and also replaced file-name-concat with concat since the former is not present in my Emacs version (27.1):

(defun my/delete-regexped-files (mask)
  ;; Delete all the files in the current directory that
  ;; match given regular expression.
  ;; Examples of mask: "\\.org~\\'", "\\.txt\\'"

(dolist (filename (directory-files "" nil mask) )
   (delete-file  filename )))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.