Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Assuming the following file structure:

/Parent1/
/Parent1/SubA/
/Parent1/SubB/
  ...
/Parent2/
/Parent2/SubA/
/Parent2/SubB/
  ...

what command can I use to recursively remove SubB from each parent directory? What I've been doing is long hand (very lame, but I'll include it just so it is clear what I'm trying to do):

rm -rf Parent1/SubB
^1^2^
...
share|improve this question
add comment

2 Answers

You can achieve this using the find and xargs commands. Let's say Parent1 and Parent2 are both stored in a directory named SuperParent. You could do something along the lines of:

find /SuperParent -name SubB -type d -print0 | xargs -0 rm -rf

This pipes a list of directories named SubB found below /SuperParent into the xargs command, which just takes each directory and runs rm with the directory as an argument.

share|improve this answer
1  
run find /SuperParent -name SubB -type d | xargs echo rm -rf first to echo what would be executed, if you're concerned. Also, if you have way too many directories, you may get an error, so you'd have to do find /SuperParent -name SubB -type d | xargs -i rm -rf {} (which executes each rm command one at a time) –  Roy Rico Mar 31 '11 at 15:11
1  
This almost worked for what I needed, and did send me down the right path. The only problem that I can see is that if there is a directory named SubB which is a child of SubA, (or a sibling of Parent1) and you did not want to delete that directory. Qualifying this with codefind /SuperParent -mindepth 2 -maxdepth 2 -name SubB -type d | xargs rm -rf`code` seems like it would take care of that problem. Thanks for your answer! –  process91 Apr 1 '11 at 10:35
    
Ah that's a good point. Nice fix! –  8088 Apr 1 '11 at 13:19
add comment

If there are not too many ParentX:

rm -rf Parent*/SubB
share|improve this answer
    
Wow, this actually worked! And it's so simple, and easy to remember! Thanks! –  process91 Apr 1 '11 at 10:37
    
@slhck It works for me if file names have spaces in them. Please provide an example where it does not work. –  Ole Tange Jul 16 '12 at 3:12
    
Oh, I stand corrected. Don't know why this was downvoted anyway. –  slhck Jul 16 '12 at 11:30
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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