Linux Tips 6: Getting rid of ViM swap (.swp) files

|
I really do love ViM, it is my favorite editor for coding, writing, and anything where I would be doing a lot of cutting, pasting, and general text manipulation. However it has a swap file feature that becomes annoying to use when you are using it remotely via SSH and experience constant disconnections; a common problem with Window's limited connection timeout settings.

While there are fixes to Window's problems, as well as the option to disable swap files, I find the solutions to either be difficult to apply or limiting to ViM's functionality. Therefore I use a simple Linux one liner to find and delete all swap files as soon as I know that I have been disconnected from a session and there are swap files lying around but everything I was working on have been saved.

The command is a combination of find and xargs: find . -name ".*.swp" | xargs rm -f

To test out the command just use find . -name ".*.swp" to see if any ViM swap files are found in the current directory. If you are happy with the files found the full command will pipe the resulting file list into xargs, which will call rm -f on each entry, thereby deleting it for you. I use this command so often that I no longer test the results of find and just delete away so that when I re-edit the files I am working I do not get the "restore, load, delete" etc. prompt from ViM.

4 comments:

Maha said...

You can also accomplish the same thing with find's -exec operator:

find . -name ".*.swp" -exec rm -f \{\} \;

Fabio Montefuscolo said...

Or

find -name "*.swp" -delete

Sebastian Gellweiler said...

A more complex, but also more secure solution, as it uses the file command to check if it is really a vim swap file and not some other file, which has the swp extension.

for var in $(find -name '*.swp' 2>/dev/null);do
is_vim_swap=$(file $var | grep -i "Vim swap file");
if [[ -n $is_vim_swap ]]; then
rm $var;
fi;
done

NeuroFuzzy said...

Haha, late comment I know, but, why use find at all?
rm .*.swp
works perfectly fine for me!

Post a Comment