How to quote arguments with xargs
I had a similar requirement and ended up using the -I
switch to have a placeholder and I was able to quote it.
find . -size +1M | xargs -I {} rm "{}"
As you're already using that non-standard 1M
, chances are your find
implementation also supports -delete
. So, simply use:
find . -type f -size +1M -delete
Where supported, that's by far the safest and most efficient.
If you insist on using xargs
and rm
with find
, just add -print0
in your command:
find . -type f -size +1M -print0 | xargs -r0 rm -f --
(-print0
and -0
are non-standard, but pretty common. -r
(to avoid running rm
at all if find
doesn't find anything) is less common, but if your xargs
doesn't support it, you can just omit it, as rm
with -f
won't complain if called without argument).
The standard syntax would be:
find . -type f -size +1048576c -exec rm -f -- {} +
Other way:
find . -type f -size +1M -execdir rm -f -- {} +
(that's safer than -exec
/xargs -0
and would work with very deep directory trees (where full file paths would end up larger than PATH_MAX
), but that's also non-standard, and runs at least one rm
for each directory that contains at least one big file, so would be less efficient).
From man find
:
-print0
True; print the full file name on the standard output, followed by a null character (instead of the newline character that
find
output. This option corresponds to the-0
option ofxargs
.
Option -0
of xargs
means that output from pipe is interpreted as null terminated items. In such case you also need to create input for the pipe with find ... -print0
.