Search code examples
bashfindxargsrm

Delete directories with specific files in Bash Script


I would like to delete specific files if existed but also the directories that contain these files. I do know the files I would like to wipe but not the directories. So far, as I'm new in bash scripting, I think of this :

find ./ -type f -name '*.r*' -print0 | xargs -0 rm -rf &> log_del.txt
find ./ -type f -name '*.c*' -print0 | xargs -0 rm -rf &>> log_del.txt

At the moment, all files named with the specific extensions *.r* and *.c* are deleted. But the directories are still remaining and also the subdirectories in it, if existed. I also thought of the option -o in find to delete in one line :

find ./ -type f \( -name '*.r*' -o -name '*.c*' \) -print0 | xargs -0 rm -rf &> log_del.txt

How can I do this? And I also see that my log_del.txt file is empty... :-(


Solution

  • It looks like what you really want is to remove all empty directories, recursively.

    find . -type d -delete
    

    -delete processes the directories in child-first order, so that a/b is deleted before a. If a given directory is not empty, find will just display an error and continue.