How can I use "mv" to gather all the files found by "find" in the same folder?
I can find all the files I want using find however I want to use mv to move them all to a certain folder. How can I do that?
2 Answers
A slight skew, cp and mv both support a -t target argument that lets you start with where your destination and end your command with a long list of things to copy or move. That lends itself perfectly to things like find -exec ... {} +, which will build a long command efficiently. Much more than find -exec ... {} \;
find . -type f -exec mv -t /new/path {} + 1 Classic approach - find + while loop
find /your/top/directory -maxdepth 1 -type f -print0 | while IFS="" read -r -d "" FILENAME; do mv -t /path/to/destination/directory "$FILENAME";doneExplanation:
findgives you the list of files ( indicated by -type to ignore directories ) in/your/top/directory, descends at maximum 1 level in the directory structure, and prints the output as null-separated string;whileloop in conjunction withreadtake each part of that null-separated string and store it to FILENAME variable.mvthrows the current file to destination directory indicated with-tflag.
This approach is very useful when you want to avoid parsing ls output, and in fact, I've learned it here.