0

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 ?

marked as duplicate by muru command-line Mar 26 '18 at 15:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4

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
3

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.

  • @pa4080 yes, I fixed my answer, thanks. – Patrick Mevzek Mar 26 '18 at 10:02
  • -a is not necessary – αғsнιη Mar 27 '18 at 1:43
  • @αғsнιη yes -a is not necessary, but not a problem either. better to show that you can do combination of logic statements – Patrick Mevzek Mar 27 '18 at 7:04
1
shopt -s globstar
echo **/*delme* | xargs rm
  • 1
    why not "rm */*delme"? Or is it because builtin echo does not have an argument limit? – Sebastian Stark Mar 26 '18 at 11:30
  • I think that every expantion is limited by certain system limits. However using of xargs may be a solution. – Josef Klimuk Mar 26 '18 at 13:57

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