Your command appears to have two issues, the first of which may not matter much in your case, but is nevertheless worth pointing out: (i) it is not generic in the sense that it will not be able to process arbitrary filenames, in particular filenames that contain newlines (i.e. \n
), and (ii) as already noted by Kusalananda, the -exec
option belongs to the find
command, and can thus not be separated therefrom as you have tried.
Using the GNU utilities, these issues can be fixed with the following pipeline, which will find the most recent file in (or below) the directory /home/user1/folder1/
and copy it to /home/user2/folder2/
:
find /home/user1/folder1/ -type f -printf '%T@ %p\0' 2>/dev/null |
sort -znk1,1 | tail -zn1 | cut -zf2- -d' ' |
xargs -0 cp -t /home/user2/folder2/
As to issue (i): note the \0
at the end of the -printf
format string, and the -z
and -0
options to the various commands in the pipeline, which ensure that the identified filename is passed in a NUL-delimited fashion, and thus enable it to include blanks and/or newlines.
As to issue (ii): you can use the xargs
command to collect arguments from stdin
and to build a new commandline with them. Part of the trick here is to use the -t
option to the cp
command, to specify the target directory before providing any filename to be copied there, since xargs
will build a commandline by appending any arguments it receives on stdin
to a given command.