Using a Linux/Unix terminal to copy many files to a new location

1

1

I'm trying to use the a Linux terminal to copy many files to a new location. I tired the command:

sudo locate -i file_I_want | xargs cp $1 /place_I_want_everything_copied_to/

Which, gives an error. What's the correct way to handle this?

InBetween

Posted 2012-02-03T16:56:41.720

Reputation: 175

Do they all have a similar name like file001.jpg file002.jpg file003.jpe? Otherwise cp should do what you want with cp -r /a/folder – jwbensley – 2012-02-03T17:04:39.060

What is the exact error? – Zoredache – 2012-02-03T17:06:03.130

@javano Yup the all have similar file names, and they're all in different folders across the system. – InBetween – 2012-02-03T17:15:32.517

@Zoredache /somedir/.../file.jpg isn't a directory (of course). But if I plug in the file path into the cp command (right where the $1 is) just like I have it up there, then it works. If xargs works like I think it does, I don't see what I'm doing wrong. Everything I've read on xargs makes me think want I have up there is correct. Apparently it's not. – InBetween – 2012-02-03T17:17:00.283

3cp $(locate -i *.jpg) /destination/folder – jwbensley – 2012-02-03T17:30:08.060

Answers

1

xargs doesn't work that way. It doesn't use $1. It normally just postpends the argument to the end of the param list. But in this case it won't work, since it's the target, not the destination and a trailing parameter is not what's needed.

Check out the -i flag to xargs, it allows you to have a substitution. The default is to use {}, I guess to be consistent with find

sudo locate -i *file_I_want* | xargs -i cp {} /place_I_want_everything_copied_to/

@javano 's comment is an answer as well, though would break if there are spaces in the filenames (though I believe spaces would break the xargs usage above as well)

Rich Homolka

Posted 2012-02-03T16:56:41.720

Reputation: 27 121