Move all files except some (file pattern) from a DOS command

eze1981 picture eze1981 · Nov 4, 2010 · Viewed 38.4k times · Source

From a DOS command I want to move all files that do not match a file name pattern. Something like this:

For example I want to move all files that do not start with "aaa"

for %i in (*) do if not %i == aaa* move %i .\..

Answer

Paul Tomasi picture Paul Tomasi · Dec 19, 2010

XCOPY is designed to work with 'exclude' lists... See below:

   dir /b /a-d "source"|findstr /b "aaa" >"%temp%\aaafiles.tmp"

   xcopy "source" "destination\" /exclude:%temp%\aaafiles.tmp /y

The first line performs a DIR (directory) listing of the source folder, listing files in bare format (/b) ignoring directory names (/a-d). The output is piped into the FINDSTR command.

FINDSTR looks at each filename and compares it's beginning (/b) with the string "aaa".

If the start of a filename matches the string "aaa", the filename is redirected (written) to the file aaafiles.tmp in the users TEMP directory.

The /b is vital because you don't want to exclude files such as theaaafile.txt.

The XCOPY command copies files from the source folder to the destination folder except files that are listed in aaafiles.tmp.

Prompting to overwrite existing files (/y) is turned off.

source and destination will need to be replaced your own foldernames.