Windows – How to move all files except the newest one to a folder

batch-filewindows

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.

Best Answer

Posting suyao's answer here:

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

The simple explanation is that the DIR command has pre-built date sorting in it.

/T (has W implied would work as well) sorts based on time Last Written
/O sets the order, -D = By Date/Time, in reverse order
/A-D only entries that are NOT directories (hence files)
/B returns simply the filename

The "skip=1" means that the code should ignore the topmost line returned, and since the files were ordered correctly, that would be the most recent file.