Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

As in the title, I would like to remove all files in the lib directory with .swp in the end.

How can I do this without find in:

rm `find lib/ -name *.swp`
share|improve this question
Why do you wish to remove 'find', academic reason or something more precise? – bbaja42 Jan 21 '13 at 22:08
I'm just curious how this can be done in other way. – Patryk Jan 21 '13 at 22:12
If you have Perl installed you can use find2perl to generate an equivalent script, which you can customise as needed. – pgs Jan 22 '13 at 0:55
up vote 4 down vote accepted

The benefit to find is that it is recursive. Some modern shells offer search recursion, but it is not in the POSIX standard, so you can not rely on them to work everywhere. Here is an example that works in bash 4.0 and higher.

shopt -s globstar
for f in **/*.swp; do
    rm -- "$f"

As far as the find command that you already have, it will break on any files that contain whitespace such as spaces. Here is a fixed example:

find lib/ -name '*.swp' -exec rm {} +

With some versions of find, you can use -delete:

find lib/ -name '*.swp' -delete
share|improve this answer
Note that that for loop above would rather be equivalent to find -L . -name '.*' ! -name . -prune -o -name '*.swp' -exec rm {} + – Stéphane Chazelas Jan 28 '13 at 23:44
cd lib && ls -R  | grep '\.swp$' | xargs -d '\n' rm

As for your original, I'd have done it:

find lib -name '*.swp' | xargs -d '\n' rm

because if find returns no results you won't get an error.

You might also want to use \! -type d so find doesn't return any directories which happen to be called *.swp, because rm would fail to remove them. You could do something similar with my alternative using ls -RF because directories would get a trailing / so not match the regex.

share|improve this answer
Both examples break on files with spaces. – jordanm Jan 21 '13 at 22:34
Does piping to xargs provide a benefit over -delete or even -exec rm {} ? – user17591 Jan 21 '13 at 22:41
fixed by setting newline as the delimiter – Jonathan Wakely Jan 21 '13 at 22:41
@user17591 - it has a benefits over -exec rm {} \; because it will execute rm one time, rather than once for each file. This benefit does not carry over to -exec rm {} +. The latter is almost always what you want. – jordanm Jan 21 '13 at 22:42
So will using + as a terminator instead of ; to -exec (POSIX, should work everywhere). – jordanm Jan 21 '13 at 22:43

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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