Search code examples
bashrm

Trying to remove a file and its parent directories


I've got a script that finds files within folders older than 30 days:

find /my/path/*/README.txt -mtime +30

that'll then produce a result such as

/my/path/jobs1/README.txt
/my/path/job2/README.txt
/my/path/job3/README.txt

Now the part I'm stuck at is I'd like to remove the folder + files that are older than 30 days.

 find /my/path/*/README.txt -mtime +30 -exec rm -r {} \; 

doesn't seem to work. It's only removing the readme.txt file

so ideally I'd like to just remove /job1, /job2, /job3 and any nested files

Can anyone point me in the right direction ?


Solution

  • This would be a safer way:

    find /my/path/ -mindepth 2 -maxdepth 2 -type f -name 'README.txt' -mtime +30 -printf '%h\n' | xargs echo rm -r
    

    Remove echo if you find it already correct after seeing the output.

    With that you use printf '%h\n' to get the directory of the file, then use xargs to process it.