Reputation: 12371
I'm working on Linux and there is a folder, which contains lots of sub directories. I need to delete all of sub directories which have a same name. For example,
dir
|---subdir1
|---subdir2
| |-----subdir1
|---file
I want to delete all of subdir1
. Here is my script:
find dir -type d -name "subdir1" | while read directory ; do
rm -rf $directory
done
However, I execute it but it seems that nothing happens.
I've tried also find dir -type d "subdir1" -delete
, but still, nothing happens.
Upvotes: 8
Views: 10093
Reputation: 49
From the question, it seems you've tried to use while
with find
. The following substitution may help you:
while IFS= read -rd '' dir; do rm -rf "$dir"; done < <(find dir -type d -name "subdir" -print0)
Upvotes: 0
Reputation: 52112
With the globstar
option (enable with shopt -s globstar
, requires Bash 4.0 or newer):
rm -rf **/subdir1/
The drawback of this solution as compared to using find -exec
or find | xargs
is that the argument list might become too long, but that would require quite a lot of directories named subdir1
. On my system, ARG_MAX
is 2097152.
Upvotes: 7
Reputation: 6517
If find
finds the correct directories at all, these should work:
find dir -type d -name "subdir1" -exec echo rm -rf {} \;
or
find dir -type d -name "subdir1" -exec echo rm -rf {} +
(the echo
is there for verifying the command hits the files you wanted, remove it to actually run the rm
and remove the directories.)
Both piping to xargs
and to while read
have the downside that unusual file names will cause issues. Also, find -delete
will only try to remove the directories themselves, not their contents. It will fail on any non-empty directories (but you should at least get errors).
With xargs
, spaces separate words by default, so even file names with spaces will not work. read
can deal with spaces, but in your command it's the unquoted expansion of $tar
that splits the variable on spaces.
If your filenames don't have newlines or trailing spaces, this should work, too:
find ... | while read -r x ; do rm -rf "$x" ; done
Upvotes: 16
Reputation: 195029
Using xargs:
find dir -type d -name "subdir1" -print0 |xargs -0 rm -rf
find|xargs
or find -exec
https://www.everythingcli.org/find-exec-vs-find-xargs/
Upvotes: 2