Question

I am trying to write a batch file to do the following tasks:

  1. I have 20 sub-folders(milk, cheese, protein...) within one folder(ABC). Each subfolder has about 15 monthly files in .csv, named as 2013-10-01, 2013-09-02, 2013-07-31.....

  2. These monthly files are added on a monthly basis and there is no pattern regarding their names, e.g., it could be the first day for October but the fourth day for November. So each month I add a new file to each subfolder, i.e., the number of files is increasing;

  3. Every month, for each subfolder/category, I want to copy the most recent 9 monthly files to another location, say, folder CDE;

  4. After copying them to folder CDE, I put them all together to one file with a unique name defined using the current time(%%d-%%e-%%f). In such way I can have the monthly file for each category every month.

I am able to write the code for step 4 and am wondering if any of you could help on step 3. I now have to manually copy and paste the 9 files from all 20 subfolders every time. It is very inefficient and I know some batch commands could definitely make the process quicker and easier.

Thank you very much!

Was it helpful?

Solution

EDIT fixed the 'copy all files' issue.

This should do the following: (change c:\cde and c:\abc)

1) copy 9 most recent files from the folder
2) merge them all into one file called foldername-HHMMSS (from the time variable)
3) The foldername-HHMMSS file is created in the c:\ABC folder
4) remove the 9 copied files
5) repeat for each folder

@echo off
set "source=D:\ABC"
set "target=C:\files\CDE"
setlocal enabledelayedexpansion
md "%target%" 2>nul
for /d /r "%source%" %%a in (*) do (
  pushd "%%a"
     set num=0
         for /f "delims=" %%b in ('dir /o-d /b /a-d') do (
           set /a num+=1
           if !num! LSS 10 copy "%%b" "%target%" >nul
         )
     set t=!time!
     set t=!t:~0,2!!t:~3,2!!t:~6,2!
     copy "%target%\*.*" "%source%\%%~nxa-!t!" >nul
     echo "%source%\%%~nxa-!t!" created from "%%a"
     if defined target del "%target%\*.*?"
  popd
)
pause

OTHER TIPS

setlocal enabledelayedexpansion
for /f "delims=" %%i in ('dir abc /b /o-d') do (set /a a=0&for /f "delims=" %%j in ('dir "abc\%%~i" /b /o-d') do (set /a a+=1&if !a! LEQ 9 (copy /Y "abc\%%~i\%%~j" cde)))

put this in the same folder that abc and cde are in
if this isn't what you wanted, would you please elaborate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top