If I want to find any files with .txt in the name, and for every match that is found copy it into the /junk folder the following could be considered to work;
find / -name "*.txt" | cp /junk
but this will not work because find will produce the results as a list, which can’t be fed into cp.
So I could use xargs to resolve this
find / -name "*.txt" | xargs cp /junk
Because xargs will change the list into one line which can be fed into cp. I also think that this command would completely finish searching through the files, 'produce the list', and only then would it run the right side of the pipe (the copy).
Alternatively (and preferably) I could use exec
find / -name ".txt" -exec cp {} /junk \;
Which would run the copy each time that a match is found, (and it would run the copy in a separate process, so the find command would continue running in parallel).
Can someone confirm that these commands and my understanding is correct?
I should add that this is for education purposes only, this is not a real life scenario.
find /-command will include the /junk directory, so files already copied will be copied again. Also, it's probably a good idea to add-ior--backup=numberedto thecp-command.xargsmight decide to run the command several times and also before the pipe is finished. Trywhile sleep 1; do echo foo; done | xargs -n 3.