Why can't xargs delete directories with spaces in their names, and how to fix that?
76 find . -type d |xargs rm -rf
77 rm -rf fire\ hydrant/
78 rm -rf wine\ glass/
79 rm -rf tennis\ racket/
80 rm -rf traffic\ light/
81 rm -rf parking\ meter/
82 rm -rf teddy\ bear/
83 rm -rf sports\ ball/
84 rm -rf cell\ phone/
85 rm -rf stop\ sign/
86 rm -rf dining\ table/
87 rm -rf potted\ plant/
Fix it using
-print0
infind
andxargs -0
inxargs
to tell both commands to use the NULL character as a separator instead of space:Here's a nice explanation of why it breaks and how this fix works from The Linux Command Line by William E. Shotts Jr.
(
-0
is the short version of the--null
option)You don't need
xargs
,find
itself can do it robustly with handling:any kind of possible filenames
without triggering
ARG_MAX
If the directories are empty, use
-delete
action:If not empty, use
rm -r
in the-exec
action:If you insist on using
xargs
, for any directory names without newline in their names you can use newline as the delimiter of incoming arguments:Best way, get files NUL separated and deal with it with
-0
option ofxargs
:For all the
rm -r
used, add-f
i.e. dorm -rf
if needed.To specifically delete all subdirectories having spaces in their name, the simplest command would be :
This is the same approach as the one heemayl already suggested, the only difference being the
-name
filtering.