Locate and delete all temporary files in user directory

command lineeditorsfilesrecursiverm

I use vim a lot, and my area has power failure a lot. So the resultant is I get many *.swp files scattered over my PC.

I want an alias of rm command that removes all files with either .swp, ~, .netrwhist, .log or .bak extensions system wide (or atleast in my home directory). The command should delete the files system wide/home directory even when I am on ~/Desktop.

How can I implement so?

Best Answer

This will delete all the files with a name ending in .swp, ~, .netrwhist, .log or .bak anywhere under your home directory. No prompt, no confirmation, no recovery, the files are gone forever.

find ~ -type f \( -name '*.swp' -o -name '*~' -o -name '*.bak' -o -name '.netrwhist' \) -delete

(I purposefully omit *.log because it sounds dangerous, this is not a common extension for temporary files and there are plenty of non-temporary files with that name.)

If your OS isn't Linux, replace -delete by -exec rm {} +.

You should perhaps configure Vim to put its swap files in a single directory by setting the directory option:

set dir=~/tmp/vim-swap-files//,/var/tmp//

Create the directory first. The // at the end makes the swap file name include the directory location of the original file, so that files with the same name in different directories don't cause a crash.

You can do the same thing for backup files with the backupdir option, though it makes a lot less sense.

If you use Emacs, set auto-save-file-name-transforms to point every file to a single directory.

(setq auto-save-file-name-transforms
      '("\\`.*\\'" "~/tmp/emacs-auto-save-files/\\&" t))
Related Question