0

I'd like to use the find command with the -exec action with the plus (+) sign (for efficiency), or with xargs to copy files from one directory to another. The following answer did not work for me. I'm under bash version: 4.3.48(1). Trying:

find . \( \( -type f -size -2M \) -o \( -type f -size 2M \) \) -exec cp '{}' ~/Pictures/test_folder '+'

or:

find . \( -type f -size -2M \) -o \( -type f -size 2M \) | xargs cp -t ~/Pictures/test_folder 

does not work for me. Maybe I've made a syntactic error of some kind, but I've already tried several variations of the above commands and I still can't get it to work. The test folder is the location where I'd like the files to be copied to.

2
  • 1
    Do you get an error? "Does not work" is not enough information, Commented Nov 8, 2017 at 4:10
  • Yes. If I enter the first command, I get: find: missing argument to -exec If I enter the second command, I get a message error for each file, i.e. cp: cannot stat './file1': No such file or directory, and only one file gets copied into the test folder. Commented Nov 8, 2017 at 4:15

1 Answer 1

3

I'd expect this to work:

find . -type f \( -size -2M -o -size 2M \) -exec cp -t ~/Pictures/test_folder {} +

(I took out the common -type f test.)

With +, the {} is expected to be the last item in an -exec command. From the GNU find manual:

Only one {} is allowed within the command, and it must appear at the end, immediately before the +. A + appearing in any position other than immediately after {} is not considered to be special (that is, it does not terminate the command).

If you use find and xargs, remember to use the -print0 and -0 options:

find ... -print0 | xargs -0 cp -t ...

With -print0, filenames are delimited with the ASCII NUL character, the only one not allowed in paths. Without this, xargs could split filenames on spaces, so a ./file1 - foo.txt would be seen as ./file1, - and foo.txt by the cp command.

4
  • So that means the comment in the link I provided about putting the {} before the pathname of the cp command was definitely wrong, assuming they were using GNU find. What I'd like to know now is how I do the same thing but with the xargs command. Commented Nov 8, 2017 at 4:53
  • @John_Patrick_Mason which comment are you talking about? No comment or answer uses -exec cp {} ... +. It's either -exec cp -t ... {} + or -exec cp {} ... \;. As for xargs, see edit.
    – muru
    Commented Nov 8, 2017 at 4:56
  • You're right, but to be fair the third comment in the link should have been more specific instead of telling the OP to just add +; to the end of the command. Commented Nov 8, 2017 at 5:04
  • Thanks muru, that solved my problem. I'm marking this as solved. Commented Nov 8, 2017 at 5:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .