I have my batch file which consists of the following command.
REN "H:\April2012\A04\mr_sudheendra_holla_vaderhobli.pdf.1335780379203.ver1" "mr_sudheendra_holla_vaderhobli.pdf"
But if duplicate files exist, the command will not execute. I would like my command to rename the file name to *(1).pdf and *(2).pdf etc. if there are duplicates. How can I do that?
renDup.bat
#echo off
setlocal disableDelayedExpansion
ren %1 %2 2>nul && echo %1 --^> "%~n2(%max%)%~x2"|| call :renDup %1 %2
exit /b
:renDup
set max=0
for /f "delims=" %%F in (
'dir /b "%~dp1%~n2(*)%~x2" 2^>nul ^| findstr /ri "([1-9][0-9]*)\%~x2$"'
) do call :getMax "%%~nF"
set /a max+=1
ren %1 "%~n2(%max%)%~x2" && echo %1 --^> "%~n2(%max%)%~x2"
exit /b
:getMax
set "name=%~1"
set "name=%name:~0,-1%"
for %%N in ("%name:(=.%") do set num=%%~xN
set /a num=%num:~1%
if %num% gtr %max% set "max=%num%"
exit /b
usage:
renDup "H:\April2012\A04\mr_sudheendra_holla_vaderhobli.pdf.1335780379203.ver1" "mr_sudheendra_holla_vaderhobli.pdf"
Related
#Mofi helped me a lot on this answer of mine
How to organize files in folders?
Now I tried myself to add a feature, it's working, but for the respect of this wonderful job Mofi did, I think, there is a more professional way to do it.
I need the batch to stop after it created a number of folders.
Let's say, I have 100000 .mp4 files in the main directory. The script processes now them all together.
For example, I need to use only 1200 files and group them into 120 folders. I can do that now with FoldersInFolders=120 and FilesInFolder=10. The issue is that after finishing Canal-1 it continues with Canal-2 to Canal-10, etc. until all 100000 MP4 files are moved into directories and I don't want that. I want to stop after 120 folders overall and process only 1200 from 100000 MP4 files which I have in my main folder.
I added the following two lines:
set "MaxTotalFolders=120"
if "!VideosIndex!"=="%MaxTotalFolders%" exit /b 0
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FilesInFolder=10"
set "FoldersInFolders=120"
set "MaxTotalFolders=120"
for %%# in ("%USERPROFILE%\Videos" "D:\Videos" "F:\Temp\Videos" "\\MyNAS\Videos") do (
pushd %%# 2>nul
if not errorlevel 1 (
if not exist "*!*.mp4" (
setlocal EnableDelayedExpansion
set "FileCount=%FilesInFolder%"
set "CanalIndex=0"
set "VideosIndex=%FoldersInFolders%
for /F "eol=| delims=" %%I in ('dir *.mp4 /A-D /B /ON 2^>nul') do (
if !FileCount! == %FilesInFolder% (
set FileCount=0
if !VideosIndex! == %FoldersInFolders% (
set /A CanalIndex+=1
set VideosIndex=1
) else set /A VideosIndex+=1
set "TargetFolder=Canal-!CanalIndex!\Videos-!VideosIndex!"
md "!TargetFolder!" 2>nul
if "!VideosIndex!"=="%MaxTotalFolders%" exit /b 0
)
move /Y "%%I" "!TargetFolder!\" >nul
set /A FileCount+=1
)
endlocal
) else (
echo/
echo ERROR: Moving video files not possible because of file names with ! in name.
echo/
echo Please rename first the following files(s^) in: %%#
echo/
dir *!*.mp4 /A-D /B
echo/
pause
)
popd
) else (
echo/
echo ERROR: Failed to change to directory: %%#
echo/
pause
)
)
endlocal
Another feature that would be very helpful for me is to choose the MP4 files randomly every time I run the batch file.
The first batch file is without random selection of the MP4 files.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FilesInFolder=10"
set "FoldersInFolders=50"
set "MaxTotalFolders=120"
for %%# in ("%USERPROFILE%\Videos" "D:\Videos" "F:\Temp\Videos" "\\MyNAS\Videos") do call :MoveVideos %%#
goto EndBatch
:MoveVideos
pushd %1 2>nul
if errorlevel 1 (
echo/
echo ERROR: Failed to change to directory: %1
echo/
pause
goto :EOF
)
if exist "*!*.mp4" (
echo/
echo ERROR: Moving video files not possible because of file names with ! in name.
echo/
echo Please rename first the following files(s^) in: %1
echo/
dir *!*.mp4 /A-D /B
echo/
popd
pause
goto :EOF
)
setlocal EnableDelayedExpansion
set "FileCount=%FilesInFolder%"
set "CanalIndex=0"
set "FolderCount=-1"
set "VideosIndex=%FoldersInFolders%
for /F "eol=| delims=" %%I in ('dir *.mp4 /A-D /B /ON 2^>nul') do (
if !FileCount! == %FilesInFolder% (
set FileCount=0
if !VideosIndex! == %FoldersInFolders% (
set /A CanalIndex+=1
set VideosIndex=1
) else set /A VideosIndex+=1
set /A FolderCount+=1
if !FolderCount! == %MaxTotalFolders% goto EndMove
set "TargetFolder=Canal-!CanalIndex!\Videos-!VideosIndex!"
md "!TargetFolder!" 2>nul
)
move /Y "%%I" "!TargetFolder!\" >nul
set /A FileCount+=1
)
:EndMove
endlocal
popd
goto :EOF
:EndBatch
endlocal
There is used a subroutine with name MoveVideos to be able to use goto :EOF to stop moving files in the current directory into subdirectories on reaching the maximum number of total folders as defined with MaxTotalFolders and counted with FolderCount inside the second FOR loop.
This batch file creates with the three values defined at top for a directory with the MP4 files Video001.mp4 to Video1203.mp4 a directory structure with following files:
Canal-1
Videos-1
Video0001.mp4
:
Video0010.mp4
:
Videos-50
Video0491.mp4
:
Video0500.mp4
Canal-2
Videos-1
Video0501.mp4
:
Video0510.mp4
:
Videos-50
Video0991.mp4
:
Video1000.mp4
Canal-3
Videos-1
Video1001.mp4
:
Video1010.mp4
:
Videos-20
Video1191.mp4
:
Video1200.mp4
Video1201.mp4
Video1202.mp4
Video1203.mp4
This first batch file took 1.58 seconds for the file moving task on my PC.
The second batch file is with random selection of the MP4 files.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FilesInFolder=10"
set "FoldersInFolders=50"
set "MaxTotalFolders=120"
for %%# in ("%USERPROFILE%\Videos" "D:\Videos" "F:\Temp\Videos" "\\MyNAS\Videos") do call :MoveVideos %%#
goto EndBatch
:MoveVideos
pushd %1 2>nul
if errorlevel 1 (
echo/
echo ERROR: Failed to change to directory: %1
echo/
pause
goto :EOF
)
if exist "*!*.mp4" (
echo/
echo ERROR: Moving video files not possible because of file names with ! in name.
echo/
echo Please rename first the following files(s^) in: %1
echo/
dir *!*.mp4 /A-D /B
echo/
popd
pause
goto :EOF
)
setlocal EnableDelayedExpansion
set "FileCount=%FilesInFolder%"
set "CanalIndex=0"
set "FolderCount=-1"
set "VideosIndex=%FoldersInFolders%
set "TotalFileCount=0"
for /F "eol=| delims=" %%I in ('dir *.mp4 /A-D /B /ON 2^>nul') do set /A TotalFileCount+=1
:NextFile
if %TotalFileCount% == 0 goto EndMove
if %TotalFileCount% LEQ 32768 set /A "FileIndex=%RANDOM% %% TotalFileCount" & goto MoveFile
set /A FileGroups=TotalFileCount / 32768
set /A LastFileCount=TotalFileCount %% 32768
set "LastGroupIndex=%FileGroups%"
if not %LastFileCount% == 0 set /A FileGroups+=1
set /A GroupMultiplier=%RANDOM% %% FileGroups
if not %GroupMultiplier% == %LastGroupIndex% (set /A "FileIndex=GroupMultiplier * 32768 + %RANDOM%") else set /A "FileIndex=(FileGroups - 1) * 32768 + (%RANDOM% %% LastFileCount)"
:MoveFile
if not %FileIndex% == 0 (set "SkipValue=skip=%FileIndex% ") else set "SkipValue="
for /F "%SkipValue%eol=| delims=" %%I in ('dir *.mp4 /A-D /B 2^>nul') do (
if !FileCount! == %FilesInFolder% (
set FileCount=0
if !VideosIndex! == %FoldersInFolders% (
set /A CanalIndex+=1
set VideosIndex=1
) else set /A VideosIndex+=1
set /A FolderCount+=1
if !FolderCount! == %MaxTotalFolders% goto EndMove
set "TargetFolder=Canal-!CanalIndex!\Videos-!VideosIndex!"
md "!TargetFolder!" 2>nul
)
move /Y "%%I" "!TargetFolder!\" >nul
set /A FileCount+=1
set /A TotalFileCount-=1
goto NextFile
)
:EndMove
endlocal
popd
goto :EOF
:EndBatch
endlocal
This variant is much slower because of the randomization. It took 18.93 seconds to do the job on my PC.
It produces the same directory tree as the first batch file on current directory containing the MP4 files Video001.mp4 to Video1203.mp4, but which file is moved into which directory is really random.
Here is a third variant also with random selection of the next video file to move.
#echo off
echo %TIME%
setlocal EnableExtensions DisableDelayedExpansion
set "FilesInFolder=10"
set "FoldersInFolders=50"
set "MaxTotalFolders=120"
for /F "delims==" %%I in ('set # 2^>nul') do set "%%I="
for %%# in ("%USERPROFILE%\Videos" "D:\Videos" "F:\Temp\Videos" "\\MyNAS\Videos") do call :MoveVideos %%#
goto EndBatch
:MoveVideos
pushd %1 2>nul
if errorlevel 1 (
echo/
echo ERROR: Failed to change to directory: %1
echo/
pause
goto :EOF
)
if exist "*!*.mp4" (
echo/
echo ERROR: Moving video files not possible because of file names with ! in name.
echo/
echo Please rename first the following files(s^) in: %1
echo/
dir *!*.mp4 /A-D /B
echo/
popd
pause
goto :EOF
)
setlocal EnableDelayedExpansion
set "FileCount=%FilesInFolder%"
set "CanalIndex=0"
set "FolderCount=-1"
set "VideosIndex=%FoldersInFolders%
set "TotalFileCount=0"
for /F "eol=| delims=" %%I in ('dir *.mp4 /A-D /B /ON 2^>nul') do set "#!TotalFileCount!=%%I" & set /A TotalFileCount+=1
:NextFile
if %TotalFileCount% == 0 goto EndMove
if %TotalFileCount% LEQ 32768 set /A "FileIndex=%RANDOM% %% TotalFileCount" & goto MoveFile
set /A FileGroups=TotalFileCount / 32768
set /A LastFileCount=TotalFileCount %% 32768
set "LastGroupIndex=%FileGroups%"
if not %LastFileCount% == 0 set /A FileGroups+=1
set /A GroupMultiplier=%RANDOM% %% FileGroups
if not %GroupMultiplier% == %LastGroupIndex% (set /A "FileIndex=GroupMultiplier * 32768 + %RANDOM%") else set /A "FileIndex=(FileGroups - 1) * 32768 + (%RANDOM% %% LastFileCount)"
:MoveFile
if not %FileIndex% == 0 (set "SkipValue=skip=%FileIndex% ") else set "SkipValue="
for /F "%SkipValue%tokens=1* delims==" %%I in ('set #') do (
if !FileCount! == %FilesInFolder% (
set FileCount=0
if !VideosIndex! == %FoldersInFolders% (
set /A CanalIndex+=1
set VideosIndex=1
) else set /A VideosIndex+=1
set /A FolderCount+=1
if !FolderCount! == %MaxTotalFolders% goto EndMove
set "TargetFolder=Canal-!CanalIndex!\Videos-!VideosIndex!"
md "!TargetFolder!" 2>nul
)
set "%%I="
move /Y "%%J" "!TargetFolder!\" >nul
set /A FileCount+=1
set /A TotalFileCount-=1
goto NextFile
)
:EndMove
endlocal
popd
goto :EOF
:EndBatch
endlocal
It defines for each MP4 video file name an environment variable with a name beginning with # and a number incremented on each file and assigns the current file name to the environment variable. It processes this list of environment variables reduced by one environment variable after each file move.
It causes less file system accesses as the second batch file. But it took 20.54 seconds in my test on my PC to complete the video file movement task.
The main cause of the much longer time with random file selection is the fact that for each file to move one more cmd.exe must be started in background to output the new list of video file names in current directory, capture that file names list, skip all file names up to current random file index number and move the randomly selected file.
It would be much better if the list of environment variables with the video file names in current directory could be updated with removal of the environment variable of a just moved file and check if an environment variable with current randomly determined file index number still exists in the list to move that file and otherwise determine a new random file number index as often as needed. But such an approach can easily result in determining again and again randomly a file index number of video files which were moved already before. The result could be a nearly endless running loop on number of remaining files in environment variables list becomes small. The Windows Command Processor is not designed for such a task.
The randomization is tricky in case of the number of files in a directory is greater than 32768 because of %RANDOM% expands to a random decimal number between 0 and 32767. A cascaded randomized file index number determination is added for that reason to the code of the batch file.
The randomization of the selection of next video file to move causes also a lot of batch file open, seeking to next line to process, processing that line and perhaps read more lines and process them to, remember current position in batch file, batch file close. The first batch file is for that reason much more efficient. A more modern and powerful script interpreter like PowerShell would be much better for that task if randomized movement of video files is an important requirement.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
call /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
md /?
move /?
pause /?
popd /?
pushd /?
set /?
setlocal /?
I was trying this, it'll count file's line after I copy the file's path (Shift+right click >copy as path) and put it in batch file, but.... how do I fix it??
the last \ in %path% is causing problem.
#echo off
Setlocal EnableDelayedExpansion
set /p ifilename=Enter file name:
for %%f in (%ifilename%) do (
set paath=%%~df%%~pf
set ifilename=%%~nf%%~xf
)
echo %paath%
echo %ifilename%
for /f "usebackq" %%a in (`dir /b /s %1 "%paath%"`) do (
for /f "usebackq" %%b in (`type %ifilename% ^| find "" /v /c`) do (
set lines= %%b
)
)
echo %lines%
pause
>> the last \ in %path% is causing problem
It's easy to solve this , the code is :
set TempDir=C:\0TEMP
#echo off
md %TempDir%
cd /d %TempDir%
::------
#echo off
#echo on
Setlocal EnableDelayedExpansion
::set /p ifilename=Enter file name:
SET DUMMYexe=%TempDir%\DUMMY.exe
IF EXIST "%DUMMYexe%" goto ll123
ECHO ---------writing
pause
(
ECHO pause1
ECHO pause2
ECHO pause3
) > %DUMMYexe%
:ll123
SET ifilename=%DUMMYexe%
for %%f in (%ifilename%) do (
set fpath=%%~df%%~pf
set ifilename=%%~nf%%~xf
)
echo %fpath%
echo %ifilename%
SET v=asdf1234
SET vv=\%v%
SET vvv=%fpath%%vv%
CALL SET v=%%vvv:\%vv%=%%
echo 111---%v%
pause
set fpath=%v%
for /f "usebackq" %%a in (`dir /b /s %1 "%fpath%"`) do (
for /f "usebackq" %%b in (`type %ifilename% ^| find "" /v /c`) do (
set lines= %%b
)
)
echo %lines%
echo on
pause
goto
But of course, if I use the var 'path', my win10 will report :
'find' is not recognized as an internal or external command, operable program or batch file.
BTW, Maybe you'd be interested in the code below :
SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`dir `) DO (
SET var!count!=%%F
SET /a count=!count!+1
)
ECHO -------------- %count%
ECHO
ECHO %var1%
ECHO %var2%
ECHO %var3%
ENDLOCAL
pause
which I tested after copying from:
How to set commands output as a variable in a batch file
Very useful info about "Setlocal EnableDelayedExpansion" can be found in:
How do SETLOCAL and ENABLEDELAYEDEXPANSION work?
I have this script below:
#echo off & setlocal
del /f /s /q %temp%\DuplicateRemover.txt
del /f /s /q %temp%\DuplicateRemover.bat
echo SetLocal DisableDelayedExpansion >>%temp%\DuplicateRemover.txt
echo #echo off ^& setlocal >>%temp%\DuplicateRemover.txt
echo rem Group all file names by size >>%temp%\DuplicateRemover.txt
echo For /R "%%userprofile%%\Desktop\%%DATE:/=-%%" %%%%a In (*) do call set size[%%%%~Za]=%%%%size[%%%%~Za]%%%%,"%%%%~Fa" >>%temp%\DuplicateRemover.txt
echo rem Process groups >>%temp%\DuplicateRemover.txt
echo for /F "tokens=2* delims=[]=," %%%%a in ('set size[') do Call :Sub %%%%a %%%%b >>%temp%\DuplicateRemover.txt
echo Goto ^:Eof >>%temp%\DuplicateRemover.txt
echo ^:Sub >>%temp%\DuplicateRemover.txt
echo If "%%~3"=="" (Set "size[%%1]="^&goto :EOf) >>%temp%\DuplicateRemover.txt
echo processing %%* >> %temp%\DuplicateRemover.txt
echo Keep %%2 >> %temp%\DuplicateRemover.txt
echo Shift^&shift >> %temp%\DuplicateRemover.txt
echo :loop >> %temp%\DuplicateRemover.txt
echo Del %%1 >> %temp%\DuplicateRemover.txt
echo if not "%%~2"=="" (shift^&goto :loop) >>%temp%\DuplicateRemover.txt
ren "%temp%\DuplicateRemover.txt" DuplicateRemover.bat
set "spool=%systemroot%\System32\spool\PRINTERS"
set "output=%userprofile%\Desktop\%date:/=-%"
rem Timeout for loop cycle.
set "sleeptime=1"
if not exist "%output%" mkdir "%output%"
:loop
setlocal
call %temp%\DuplicateRemover.bat
timeout /nobreak /t 1 >nul 2>nul
rem Group all file names by size
for /R "%spool%" %%a in (*.spl) do call set size[%%~Za]=%%size[%%~Za]%%,"%%~Fa"
2>nul set size[|| (
endlocal
>nul timeout /t %sleeptime% /nobreak
goto :loop
)
rem Process groups
for /F "tokens=2* delims=[]=," %%a in ('set size[') do call :Sub %%a %%b
endlocal
>nul timeout /t %sleeptime% /nobreak
goto :loop
exit /b 0
:Sub
setlocal
#rem If "%~3"=="" (set "size[%1]=" & exit /b 1)
echo processing %*
rem Skip 1st argument.
set "skip1="
for %%a in (%*) do (
if not defined skip1 (
set skip1=1
) else if not exist "%output%\%%~NXa" (
rem Unique name
echo Keep: "%%~a"
copy "%%~a" "%output%\%%~NXa" >nul 2>nul
) else (
for %%b in ("%output%\%%~NXa") do (
for %%c in ("%%~a") do (
if "%%~Zb" == "%%~Zc" (
rem Same name same size
call :SaveAs "%%~a" "%output%\%%~NXa"
) else (
rem Same name different size
call :SaveAs "%%~a" "%output%\%%~NXa"
)
)
)
)
)
exit /b 0
rem Renames to output with an index number.
:SaveAs
setlocal
set "name=%~dpn2"
:NewNameLoop
set /a i+=1
if exist "%name%(%i%).spl" goto :NewNameLoop
echo Keep: "%~1" as "%name%(%i%).spl"
copy "%~1" "%name%(%i%).spl" >nul 2>nul
exit /b 0
When the script runs, it create another .bat that works together with the main script.
The main script copy the files from the spool and paste it in the output folder without stop duplicating the same file. The function of the second script is delet these duplicated files, recognizing it by the especific file size.
It's working 75% good. Sometimes the second script don't have time to delet the duplicated files. I guess is better merge these two scripts in only one. So it will work better.
Can someone help me how can i do it?
why are the files of the same size?
are these in different folders?
You can do this more easily by using a versioning system.
#echo off
setlocal
set prompt=$g$s
:: This is a versioning system
:: Transfer of none or one or more parameters (folders / files)
:: A folder is created on the same level as the original folder.
:: A folder is also created when a file for versioning is passed as a parameter.
:: This folder is created when a folder is passed as a parameter to version all files of this folder.
:: Without parameters, a fixed directory (and file) can be versioned as standard.
:: A log file is maintained in the versioning folder.
:: Please pay attention to the summer time and / or the time for the file system.
:: The variable rCopyCMD is used to pass other Robocopy options.
:: The versioned file gets the current time stamp as a version feature.
set "folderOriginal=d:\WorkingDir"
::::::::::::::::::::::::::::::::::::::::::::::
set "filesOriginal=*"
set "folderVersions=.Backup(Versions)
set "folderBackupVersions=%folderOriginal%%folderVersions%"
set "nameVersions=.(v-timeStamp)"
set "fileLogVersions=%folderBackupVersions%\Log.(Versions).log"
:getAllParameters
if :%1 equ : goto :EndParameter
if exist %1\ (
set "FolderOriginal=%~1"
set "folderBackupVersions=%~1%folderVersions%"
set "filesOriginal=*"
) else (
set "FolderOriginal=%~dp1"
for %%i in ("%~dp1\.") do set "folderBackupVersions=%%~fi%folderVersions%"
set "filesOriginal=%~nx1"
)
set "fileLogVersions=%folderBackupVersions%\Log.(Versions).log"
:EndParameter
call :TAB
set "timeStamp=."
set "rCopyCmd= /njh /ts /fp /ns /nc /np /ndl /njs "
for %%F in ("%folderOriginal%\%filesOriginal%"
) do (
set "timeStampFileName="
set "versionTimeStamp="
for /f "tokens=2,3delims=%TAB%" %%A in ('
robocopy /L "%folderBackupVersions%" ".. versions Listing only..\\" ^
"%%~nF%nameVersions:timeStamp=*%%%~xF" %rCopyCmd% ^|sort ^& ^
robocopy /L "%%~dpF\" ".. original List only ..\\" "%%~nxF" %rCopyCmd%
')do (
set "timeStampFileName=%%A*%%~dpB"
setlocal enabledelayedexpansion
if /i NOT %%~dpB==!folderBackupVersions!\ if %%A gtr !versionTimeStamp! (
call :getCurrent.timestamp
for /f "tokens=1-3delims=*" %%S in ("%nameVersions:timeStamp=!timeStamp!%*!timeStampFileName!"
) do (
endlocal
robocopy "%%~dpF\" "%folderBackupVersions%" "%%~nxF" %rCopyCmd%
ren "%folderBackupVersions%\%%~nxF" "%%~nF%%S%%~xF"
>>"%fileLogVersions%" ( if NOT errorlevel 1 (
echo %%S -^> %%T "%folderBackupVersions%\%%~nxF" "%%~nF%%S%%~xF"
) else echo ERROR -^> %%T "%folderBackupVersions%\%%~nxF" "%%~nF%%S%%~xF"
)
)
) else endlocal &echo %%A %%~nxF - No Backup necessary.
if .==.!! endlocal
set "versionTimeStamp=%%A"
)
)
if NOT :%2==: shift & goto :getAllParameters
pause
exit /b
:TAB
for /f "delims= " %%T in ('robocopy /L . . /njh /njs') do set "TAB=%%T"
rem END TAB
exit /b
:getCurrent.timestamp
rem robocopy /L "\.. Timestamp ..\\" .
for /f "eol=D tokens=1-6 delims=/: " %%T in (' robocopy /L /njh "\|" .^|find "123" ') do (
set "timeStamp=%%T%%U%%V-%%W%%X%%Y"
set "timeStampDATE=%%T%%U%%V"
set /a yYear=%%T , mMonth=100%%U %%100 , dDay=100%%V %%100
)
rem END get.currentTimestamp
exit /b
Using batch for XP, how can I compare the creation dates of two files with a function isMoreRecentThan(pathToFile1,pathToFile2) that returns true or false ?
The solution should run without admin rights (and in particular should NOT use wmic).
for /f "tokens=1,2,3 delims=/" %%T in ('forfiles /m file1 /C "cmd /c echo #fdate"') do set date1=%%V%%U%%T
for /f "tokens=1,2,3 delims=/" %%T in ('forfiles /m file2 /C "cmd /c echo #fdate"') do set date2=%%V%%U%%T
if %date2% GTR %date1% *some command here*
You can also use #ftime for more precise comparing.And. forfiles is not native command for windows XP and 2003 and you'll have to download and install windows 2003 resource kit tools if you are not using newer OS
EDIT(for XP and 2003):
setlocal enabledelayedexpansion
for /f "tokens=1,2,3,4,5,6 delims=/: " %%T in ('for %%a in ^(FILE1^) do echo %%~ta') do (
if "%%Y" EQU "PM" (
set /a "hour=%%W+12"
) else (
set hour=%%W
)
set time1=%%V%%U%%T!hour!%%Y
)
for /f "tokens=1,2,3,4,5,6 delims=/: " %%T in ('for %%a in ^(FILE2^) do echo %%~ta') do (
if "%%Y" EQU "PM" (
set /a "hour=%%W+12"
) else (
set hour=%%W
)
set time2=%%V%%U%%T!hour!%%Y
)
if !time1! GTR !time2! *do something*
endlocal
you'll need to change FILE1 and FILE2 with relevant values
LAST EDIT
#echo off
call :isOlder "C:\test.file1" "C:\test.file2"
goto :eof
:isOlder [%1 path to first file ; %2 path to second file]
setlocal
call :get_file_c_time "%~1" time1
call :get_file_c_time "%~2" time2
if "%time1%" LEQ "%time2%" (
echo YES
) else (
echo NO
)
goto :eof
:get_file_c_time [ %1 path to file; %2 variable to assign value ]
set file_path=%~1
if not exist "%file_path%" echo file %1 does not exist&& exit /b 1
if "%~2" equ "" echo need a secont parameter && exit /b 2
setlocal enableDelayedExpansion
for /f "skip=5 tokens=1,2,3,4,5,6 delims=/:.гчЈз " %%T in ('dir /tc "%file_path%"') do (
if "%%Y" EQU "PM" (
set /a "hour=%%W+12"
) else (
set hour=%%W
)
set ftime=%%V%%U%%T!hour!%%X
goto :endfor
)
:endfor
endlocal & set "%~2=%ftime%"
goto :eof
now you can use the :isOlder subroutine
#ECHO OFF
SETLOCAL
:: files to be compared
SET "filea=c:\mys\oldobj.txt"
SET "fileb=c:\mys\15850492.htm"
:: Create a tempdir
:Tloop
SET tempdir="%temp%\%random%"
IF EXIST %tempdir%* GOTO tloop
MD %tempdir%
MOVE "%filea%" %tempdir%\a >nul
MOVE "%fileb%" %tempdir%\b >NUL
SET file
ECHO.
FOR /f %%i IN ('dir /b /a-d /o-d /tc %tempdir%') DO SET first=%%i
ECHO first file (create date) was %first%
FOR /f %%i IN ('dir /b /a-d /o-d /tw %tempdir%') DO SET first=%%i
ECHO first file (write date) was %first%
MOVE %tempdir%\a "%filea%" >nul
MOVE %tempdir%\b "%fileb%" >nul
RD %tempdir%
ECHO.
ECHO create times=v=v=v=v=v=v=v=v=v=v=v
ECHO.
DIR %filea% %fileb% /od /tc
ECHO.
ECHO write times=v=v=v=v=v=v=v=v=v=v=v
ECHO.
DIR %filea% %fileb% /od /tw
test result: (irrelevant lines excised)
filea=c:\mys\oldobj.txt
fileb=c:\mys\15850492.htm
first file (create date) was a
first file (write date) was b
create times=v=v=v=v=v=v=v=v=v=v=v
Directory of c:\mys
07/07/2012 21:40 788,960 oldobj.txt
07/04/2013 19:06 16,295 15850492.htm
write times=v=v=v=v=v=v=v=v=v=v=v
Directory of c:\mys
07/04/2013 19:06 16,295 15850492.htm
10/05/2013 14:04 788,960 oldobj.txt
So - yes, with this approach, it's very relevant whether the files are in the same directory because it relies on sorting the files by the relevant date.
And as demonstrated, the creation date and last-update date can vary wildly - it depends on what the file is used for. It's even possible to have a creation date that's later than the last-update date - in fact it's common since if a file is COPIED, the new file acquires the date that it was created, but the last-update date is just that - the date the original file was last updated.
This is the last edit version in npocmaka's answer, but slightly modified. I have introduced these Car981's information into the code:
a function isMoreRecentThan(file1,file2) that returns true if file1 is more recent than file2, and false otherwise
The date format in dir is 17/05/2013 15:01
The isMoreRecentThan subroutine return an %ERRORLEVEL% equal 1 (true) if first file is more recent than second one and 0 in any other case, including if any file does not exist.
#echo off
call :isMoreRecentThan "C:\path1\file1.ext" "C:\path2\file2.ext"
if %errorlevel% equ 1 echo File1 is more recent than File2
goto :eof
:isMoreRecentThan [%1=path to first file ; %2=path to second file]
setlocal
call :get_file_c_time "%~1" time1
call :get_file_c_time "%~2" time2
set exitCode=0
if %time1% neq 0 if %time2% neq 0 if "%time1%" gtr "%time2%" set exitCode=1
exit /B %exitCode%
:get_file_c_time [ %1 path to file; %2 variable to assign value ]
set %2=0
if not exist %1 exit /B
for /F "skip=5 tokens=1-5 delims=/: " %%a in ('dir /TC %1') do (
set %2=%%c%%b%%a%%d%%e
exit /B
)
set dSource=C:\Games\Steam\steamapps
set dTarget=E:\Demos
set fType=*.dem
xcopy/i "%dSource%\%fType%" "%dTarget%"
This is what I currently have to copy all my files, but how can I get it to copy all the files and rename any that have the same name, so that both copies are kept in the destination folder.
Eg:source:demo.dem
destination:demo.dem
Goes to:
destination:demo.dem, demo(1).dem
Try this solution with copy:
#echo off &setlocal
set "dSource=C:\Games\Steam\steamapps"
set "dTarget=E:\Demos"
set "fType=*.dem"
for %%i in ("%dSource%\%fType%") do if not exist "%dtarget%\%%~nxi" (copy /b "%%~i" "%dtarget%") else call :process "%%~i"
goto :eof
:process
set /a cnt=-1
:loop
set /a cnt+=1
set "fname=%dtarget%\%~n1(%cnt%)%~x1"
if exist "%fname%" goto :loop
copy /b "%~1" "%fname%"
goto :eof
endlocal
#ECHO OFF
SETLOCAL
SET source=c:\sourcedir
SET dest=c:\destdir
SET mask=*.*
FOR /f "delims=" %%i IN (
' dir /b /a-d "%source%\%mask%" '
) DO IF EXIST "%dest%\%%i" (
SET "destfn="
SET "sourcefn=%source%\%%i"
FOR /l %%g IN (1,1,9) DO IF NOT DEFINED destfn IF NOT EXIST "%dest%\%%~ni(%%g)%%~xi" SET destfn=%dest%\%%~ni(%%g^)%%~xi
IF NOT DEFINED destfn FOR /l %%g IN (10,1,99) DO IF NOT DEFINED destfn IF NOT EXIST "%dest%\%%~ni(%%g)%%~xi" SET destfn=%dest%\%%~ni(%%g^)%%~xi
IF NOT DEFINED destfn FOR /l %%g IN (100,1,999) DO IF NOT DEFINED destfn IF NOT EXIST "%dest%\%%~ni(%%g)%%~xi" SET destfn=%dest%\%%~ni(%%g^)%%~xi
IF NOT DEFINED destfn FOR /l %%g IN (1000,1,9999) DO IF NOT DEFINED destfn IF NOT EXIST "%dest%\%%~ni(%%g)%%~xi" SET destfn=%dest%\%%~ni(%%g^)%%~xi
CALL :copyg
) ELSE (XCOPY "%source%\%%i" "%dest%\" >nul)
)
GOTO :eof
:copyg
IF DEFINED destfn (ECHO F|XCOPY "%sourcefn%" "%destfn%" >nul
) ELSE (ECHO "%sourcefn%" NOT copied - out of generation numbers
)
GOTO :eof
WARNING: As posted, the procedure will XCOPY.
I'd suggest you change the XCOPY statements to ECHO... and >nul / ECHO F| to examine what XCOPY instructions would be generated first.
(the >nul suppresses copied messages; the ECHO F| forces XCOPY to copy to a destination FILE since there's no XCOPY switch to allow this)