Batch file to move files by date modified

I wrote a batch file that creates empty folders for each date. My next task is to create another batch file that moves each file in the directory to the appropriate folder with the date, depending on their date. I read numerous forums and articles on how I can achieve this, but with my limited knowledge of the batch file, I just can't get it to work. The code I'm showing now is shown below, although this does not seem to result in a date change. Any help is much appreciated!

SET directory="\directory\path\archive" FOR /f %%a in ('dir /b "%directory%"') do ( SET fdate=%%~Ta MOVE "%directory%\%%a" "%directory%\%fdate%" 
+4
source share
1 answer

Until you provide more information about the date format, I cannot give a definitive answer. But I can show you how I will do it in my car.

I use the yyyy-mm-dd format in file and folder names, so December 13, 2011 will be 2011-12-13. My machine uses the mm / dd / yyyy format for dates (12/13/2011). Therefore, I will need to translate the output of %% ~ tF from 12/13/2011 to 2011-12-13. Note - / cannot be used in file or folder names.

So this code will do what you want on my machine:

 set "source=\directory\path\archive" set "targetRoot=\directory\path\archive" for %%F in ("%source%\*") do ( for /f "tokens=1,2,3 delims=/ " %%A in ("%%~tF") do ( move "%%~fF" "%targetRoot%\%%C-%%A-%%B" ) ) 

Addition . The question in the comment requires the method to leave a pad number with zeros to create a dir. I see two simple choices. (It really should be a different question)

This first method is simple but tedious and impractical as a general solution.

 for %%A in (01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31) do ... 

The second method is a general solution. Since your assignment is in parentheses, you need to use a delayed extension.

 setlocal enableDelayedExpansion for /l %%A in (1 1 31) do ( set "day=0%%A" set "day=!day:~-2! ... ) 

You increase the number of leading zeros by adding more than 0 to the front, and then increasing the number of characters that you save in the substring operation.

BUT - why fill out catalogs? Your strategy will add days of directories that do not exist on the calendar, plus you will likely have many unused folders for which files have not been changed on that day. It is better to create folders only as needed. Then, an addition has already been made for you, and no unnecessary folders are created.

 set "source=\directory\path\archive" set "targetRoot=\directory\path\archive" for %%F in ("%source%\*") do ( for /f "tokens=1,2,3 delims=/ " %%A in ("%%~tF") do ( if not exist "%targetRoot%\%%C\%%A\%%B" mkdir "%targetRoot%\%%C\%%A\%%B" move "%%~fF" "%targetRoot%\%%C\%%A\%%B" ) ) 
+11
source

Source: https://habr.com/ru/post/1386087/


All Articles