Ubuntu – deleting folders with spaces in their names using xargs

command linefindxargs

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/

Best Answer

Fix it using -print0 in find and xargs -0 in xargs to tell both commands to use the NULL character as a separator instead of space:

find . -type d -print0 | xargs -0 rm -rf

Here's a nice explanation of why it breaks and how this fix works from The Linux Command Line by William E. Shotts Jr.

Dealing With Funny Filenames

Unix-like systems allow embedded spaces (and even newlines!) in filenames. This causes problems for programs like xargs that construct argument lists for other programs. An embedded space will be treated as a delimiter, and the resulting command will interpret each space-separated word as a separate argument. To overcome this, find and xarg allow the optional use of a null character as argument separator. A null character is defined in ASCII as the character represented by the number zero (as opposed to, for example, the space character, which is defined in ASCII as the character represented by the number 32). The find command provides the action -print0, which produces null-separated output, and the xargs command has the --null option, which accepts null separated input. Here’s an example:

find ~ -iname '*.jpg' -print0 | xargs --null ls -l

Using this technique, we can ensure that all files, even those containing embedded spaces in their names, are handled correctly.

(-0 is the short version of the --null option)