Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

find

shell

mv

xargs

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.

like image 931
zjhui Avatar asked Dec 16 '12 08:12

zjhui


3 Answers

With BSD xargs (for OS X and FreeBSD), you can use -J which was built for this:

find . -name some_pattern -print0 | xargs -0 -J % mv % target_location 

That would move anything matching some_pattern in . to target_location

With GNU xargs (for Linux and Cygwin), use -I instead:

find . -name some_pattern -print0 | xargs -0 -I % mv % target_location 

The deprecated -i option of GNU xargs implies -I{} and can be used as follows:

find . -name some_pattern -print0 | xargs -0 -i mv {} target_location 

Note that BSD xargs also has a -I option, but that does something else.

like image 73
rakaur Avatar answered Oct 06 '22 09:10

rakaur


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.

like image 25
Jonathan Leffler Avatar answered Oct 06 '22 07:10

Jonathan Leffler


find ./ -maxdepth 1 -name "some-dir" -type d -print0 | xargs -0r mv -t x/

find: with option -print0, the output will end with '\0';

xargs: with option -0, it will split args by '\0' but whitespace, -r means no-run-if-empty, so you will not get any errors if find didn't get any output. (The -r is a GNU extension.)

I usually use this in scripts when I'm not sure if the target files exist or not.

like image 41
Evans Y. Avatar answered Oct 06 '22 07:10

Evans Y.