3

I am trying to find and delete all .swp files in my current directory. I was using below command:

rm -i `find . | grep .swp$`

But everytime it is giving me this error:

rm: missing operand
Try `rm --help' for more information.

Anything wrong I am doing?

2
11

The error message you received probably indicates that no file matched the name pattern .swp$. A generally safer way to do what you wrote (because it will handle any file name):

find . -name '*.swp' -print0 | xargs -0 rm -i --

In the snippet above, I used -print0 so that find separates records with null characters; the default is newlines, which unfortunately is valid within a filename. With -print0, the command works works with any filenames, including any that embed newlines. Likewise, xargs -0 processes its input as null-separated records.

0
10

Or a variation with find alone e.g.:

find . -name "*.swp" -ok rm {} +

or just without confirmation (WARNING!):

find . -name "*.swp" -delete
2
  • 1
    Hah, I was thinking of posting the same, but then figured I would wait for comments, if any :). Note that POSIX find doesn't support closing a -ok command with +; I would write -ok rm -- {} \; instead. – dhag Apr 27 '15 at 20:25
  • Thanks for the POSIX hint! I'm on OSX atm so I expected other limitations anyway. :) – FloHimself Apr 27 '15 at 20:28
1

Always use the simplest tool for the job. As you want to operate on the current directory only, this command will work fine:

rm -i *.swp

2
  • 1
    This command is different from what the OP is doing, since find by default will recurse into subdirectories to find matching files. – user Apr 28 '15 at 9:06
  • 1
    The OP wrote, verbatim: "I am trying to find and delete all .swp files in my current directory." He didn't specify that he wants to delete files in subdirectories also. As per OP's specifications, the rm command I posted is the best choice. – dr_ Apr 28 '15 at 9:11
0

If you want to be more restricted, you can use this:

find . -type f -name "*.swp" -exec rm -f {} \;
2
  • -0 for using exec – Michael Durrant Apr 27 '15 at 20:37
  • @MichaelDurrant What's wrong with using exec? – Erathiel Apr 28 '15 at 8:36
0

Sometimes swap files don't have .swp extension only. It may have saw, swb, swp, etc extensions as well.

sushil@batpod:/app/DDB# ls -a
.gui.py.swo
gui.py
.serializers.py.swp
serializers.py
.tcinfo.py.swm
tcinfo.py
.views.py.swb
views.py

and so on...

I have created one command which deletes almost all swap files with extension sw*

Command:

find . -name '*.sw\*' | xargs -i rm {}

NOTE: Before executing above command first have a look at the files command is going to delete, using

find . -name '*.sw\*'

Hope you don't delete some important files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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