Use xargs to mv a directory from find results into another directory

zjhui picture zjhui · Dec 16, 2012 · Viewed 46.5k times · Source

I have the following command:

find . -type d -mtime 0 -exec mv {} /path/to/target-dir \;

This will move the directory founded to another directory. How can I use xargs instead of exec to do the same thing.

Answer

Jonathan Leffler picture Jonathan Leffler · Dec 16, 2012

If you've got GNU mv (and find and xargs), you can use the -t option to mv (and -print0 for find and -0 for xargs):

find . -type d -mtime -0 -print0 | xargs -0 mv -t /path/to/target-dir

Note that modern versions of find (compatible with POSIX 2008) support + in place of ; and behave roughly the same as xargs without using xargs:

find . -type d -mtime -0 -exec mv -t /path/to/target-dir {} +

This makes find group convenient numbers of file (directory) names into a single invocation of the program. You don't have the level of control over the numbers of arguments passed to mv that xargs provides, but you seldom actually need that anyway. This still hinges on the -t option to GNU mv.