windowsbatch-filemove

How to move all files except the newest one to a folder?


I have a Windows box and a folder containing such files:

2010-07-04  20:18                81 in01_Acct_20100704001.r
2010-07-07  05:45               165 in01_Acct_20100706001.r
2010-07-07  19:41                82 in01_Acct_20100707001.r
2010-07-07  10:02                81 in01_Acct_20100707002.r
2010-07-08  08:31                89 in01_Acct_20100708001.r
2010-07-10  04:51                82 in01_Acct_20100709001.r

and I want to use a batch to periodically move all these files to another folder except the newest one (i.e. in01_Acct_20100709001.r), because this file is sometimes still being written on and moving it might lead file override in the destination folder in the next run of the batch, and causes file content lost.

Any ideas about this case would be greatly appreciated.


Solution

  • I think this batch script might do it:

    dir /TW /O-D /A-D /B > %TEMP%\tempFiles.txt
    for /F "skip=1" %f IN (%TEMP%\tempFiles.txt) DO mv %f wherever
    del %TEMP%\tempFiles.txt
    

    To explain what this does:

    1. Does a listing of the files, sorted by modified time (newest first) "/TW /O-D", skips directories "/A-D" and stores in a temporary file.
    2. Iterates through each line of the temporary file, skipping the first line (the newest file), doing the mv command on each.
    3. Deletes your temporary file.

    Edit: As per the comment, here's the one line version -- you can insert the dir command into your for loop:

    for /F "skip=1" %f IN ('dir /TW /O-D /A-D /B') DO mv %f wherever