2

I have the following files and directories configuration:

-Parent_dir
    |-delme_dir
    |-delme_file
    |-aFile
    |-sub_dir
        |-delme_dir
        |-delme_file
        |-aFile
        |-sub_dir
            |-delme_dir
            |-delme_file
            |-aFile
    |-sub_dir2
        |-delme_dir
        |-delme_file
        |-aFile

Is there a command that I can use from the Parent_dir to recursively remove all the delme_dir directories and the delme_file files ?

3 Answers3

6

In single command you could do this:

find . \( -type d -name "delme_dir" -o -type f -name "delme_file" \) -delete

If there is no other directories or files match with pattern delme_*, you can do in short.

find . -name "delme_*" -delete
αғsнιη
  • 35,660
4

You can combine find, xargs and rm:

find . -type f -a -name delme_files -print0 | xargs -0 rm

and

find . -type d -a -name delme_dir -print0 | xargs -0 rmdir

(when you are in the Parent_dir directory)

There is probably a way to combine the two find into only one but I find it clearer like that anyway.

The find commands will find the directories/files named per your example, and you pipe the results to xargs that will execute rm (remove) / rmdir (remove directory) on each of the file find "upstream", that is from the file command.

If the directories are not empty, replace rmdir by rm -Rf but this will remove recursively all files in the directories found by the find command.

The combo -print0 / -0 will make sure that all files/directories will be dealt correctly, even those having spaces in their names (maybe not needed here but better to use in generic cases).

Make sure to test things before on non important data and always have backups.

2
shopt -s globstar
echo **/*delme* | xargs rm
Josef Klimuk
  • 1,596