1

I know I can do

find . -name '*.pyc' -delete

But when I'm loooking for specific directories, -delete fails reporting that directories are not empty.

Is it possible to force find to delete non empty directories? I don't want to uses -exec rm -rf '{}' because it seems more mistake-prone to me.

  • My answer was not correct - deleted. I believe if you are looking for directories, the only real way to prune them is with "find . -type d -name 'directory*' -exec rm -rf '{}'" as you suggest. – carveone Dec 11 '13 at 18:22
  • find . -type d -name '*foo' -print | xargs rm -rf; If you are concerned with spaces in names pipe to ... | while read d; do rm -rf $d; done instead of xargs. If you know the directories are empty, use rmdir instead of rm -r – mpez0 Dec 11 '13 at 18:36

1 Answers1

1
find . \( -name '*.pyc' -o -path '*.pyc/*' \) -delete

If a directory matches -name '*.pyc' then everything inside matches -path '*.pyc/*'. And the other way around: if something matches -path '*.pyc/*' then there is a directory that matches -name '*.pyc' somewhere above it. We use logical OR (-o) to delete objects of either kind.

Notes:

  • You need brackets because of this: Why does find in Linux skip expected results when -o is used?
  • -delete implies -depth, so objects are deleted in the right order.
  • Warning: find . … should work well but find path … may not. Consider

    find /mnt/a.pyc/foo/ \( -name '*.pyc' -o -path '*.pyc/*' \) -delete
    

    The -path '*.pyc/*' will match everything while -name '*.pyc' may match nothing. In this case the command will delete more than you expect.

  • -delete is not required by POSIX. Portable solution needs -exec rm … or xargs. I don't know what you mean by "more mistake-prone". Your -exec rm -rf '{}' seems almost fine. After adding -- it seems completely fine to me:

    find . -name '*.pyc' -prune -exec rm -rf -- {} +
    

    I used -prune to avoid this scenario: Delete files and directories by their names. No such file or directory.

Kamil Maciorowski
  • 69,815
  • 22
  • 136
  • 202