Find and copy files to a single directory, automatically renaming to avoid collisions #

xxcopy c:\ h:\ /SG /IN:*.doc /IN:*.txt

Copies all doc and txt files from c: and its subdirs to the root of h:, renaming when necessary to avoid filename collisions. (The /SG switch gathers files into a single directory, sorted with newest file first.)

If filename collision is not a concern, something like this bash one-liner will do:

find . -type f \( -iname "*.doc" -o -iname "*.txt" \) -exec cp {} /mnt/ \;

UPDATE:

Here's a bash one-liner by Johannes Weiß that prevents filename collisions by prepending "z-" to duplicate filenames:

target="/tmp/target"; find ./ -type f -iname "*.doc" | while read line; do outbn="$(basename "$line")"; while true; do if [[ -e "$target/$outbn" ]]; then outbn="z-$outbn"; else break; fi; done; cp "$line" "$target/$outbn"; done

Successfully tested under bash 4.3 and OS X's antiquated bash 3.2.

Another option for finding, copying, and automatically renaming identical filenames is Automator. Since the Finder automatically increments identical filenames when copying, this workflow will do the trick:

Automator - flatten directory workflow
Files & Folders > Find Finder Items (select directory to search and set Name to "contains" with desired extension (e.g., .png)) > Copy Finder Items (select destination directory and DO NOT check "Replacing existing files") > Run

Actually, it turns out that not even Automator is required; simply open a Finder window, perform a search of the source folder for desired file extension, highlight the results, and drag to desired destination - identical filenames will be incremented automatically.

More on flattening folders:

/windows | Oct 06, 2011


Subscribe or visit the archives.