I want to know exactly what {} \;
and {} \+
and | xargs ...
do. Please clarify these with explanations.
Below 3 commands run and output same result but the first command takes a little time and the format is also little different.
find . -type f -exec file {} \;
find . -type f -exec file {} \+
find . -type f | xargs file
It's because 1st one runs the file
command for every file coming from the find
command. So, basically it runs as:
file file1.txt
file file2.txt
But latter 2 find with -exec
commands run file command once for all files like below:
file file1.txt file2.txt
Then I run the following commands on which first one runs without problem but second one gives error message.
find . -type f -iname '*.cpp' -exec mv {} ./test/ \;
find . -type f -iname '*.cpp' -exec mv {} ./test/ \+ #gives error:find: missing argument to `-exec'
For command with {} \+
, it gives me the error message
find: missing argument to `-exec'
why is that? can anyone please explain what am I doing wrong?
no, the difference between +
and \;
should be reversed. +
appends the files to the end of the exec command then runs the exec command and \;
runs the command for each file.
The problem is find . -type f -iname '*.cpp' -exec mv {} ./test/ \+
should be find . -type f -iname '*.cpp' -exec mv {} ./test/ +
no need to escape it or terminate the +
xargs I haven't used in a long time but I think works like +.
The standard equivalent of find -iname ... -exec mv -t dest {} +
for find
implementations that don't support -iname
or mv
implementations that don't support -t
is to use a shell to re-order the arguments:
find . -name '*.[cC][pP][pP]' -type f -exec sh -c '
exec mv "$@" /dest/dir/' sh {} +
By using -name '*.[cC][pP][pP]'
, we also avoid the reliance on the current locale to decide what's the uppercase version of c
or p
.
Note that +
, contrary to ;
is not special in any shell so doesn't need to be quoted (though quoting won't harm, except of course with shells like rc
that don't support \
as a quoting operator).
The trailing /
in /dest/dir/
is so that mv
fails with an error instead of renaming foo.cpp
to /dest/dir
in the case where only one cpp
file was found and /dest/dir
didn't exist or wasn't a directory (or symlink to directory).
I encountered the same issue on Mac OSX, using a ZSH shell: in this case there is no -t
option for mv
, so I had to find another solution.
However the following command succeeded:
find .* * -maxdepth 0 -not -path '.git' -not -path '.backup' -exec mv '{}' .backup \;
The secret was to quote the braces. No need for the braces to be at the end of the exec
command.
I tested under Ubuntu 14.04 (with BASH and ZSH shells), it works the same.
However, when using the +
sign, it seems indeed that it has to be at the end of the exec
command.
find . -name "*.mp3" -exec mv --target-directory=/home/d0k/??????/ {} \+
Source: Stackoverflow.com