• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Batch file help - Comparing filenames

Kelemvor

Lifer
Howdy all,

Trying to come up with a batch file that will delete a file if there is more than one in a folder.

so if I go into folder ABC, I will generally find files called ABC1234, ABC1235, etc.

All I want to do is see if there is more than 1 file in there and if so, delete the older file(s). There should never be more than 3 files in a folder.

My thought is a for loop that would go through the list of file names from a Dir /o-d command, add the filenames to variables (file1, file2, file3), and then just delete anything in the variables other than 1.

Problem is I'm not sure how to implement the counuer as it's not working.

Here's what I have:

Code:
set cnt=0
for /f %%x in ('dir /b /o-d') do (
  set /a cnt+=1
  set file%cnt% = %%x
  )

The problem is the cnt variable doesn't seem to ever change from 0 which is what it's set to up above.

It's usually something obvious that I'm missing so if anyone has any help for me, that'd be great.

Or if you have a far better way of doing this same thing, that'd be great too.
 
You can set cnt using the syntax you show, but to take its value I believe you need the % delimeters, i.e.

set /a cnt = %cnt% + 1
 
Your counter not incrementing is due to the fact that it's in the loop. You need to enabledelayed expansion.

I'm not sure why you need to assign every file to a variable, or even why you need to store the filenames at all. Maybe there's a requirement for that.

Additionally, there's also probably some limit to the number of environment variables you could have. It may be higher than you'll ever hit, but I don't like storing stuff I don't have to.

here's my variation of your code:
Code:
@ECHO OFF
setlocal enabledelayedexpansion

set /a cnt=0
for /f %%x in ('dir /b /o-d') do (
	set /a cnt+=1
REM	here just do if > number of files to keep then delete file
)
endlocal
 
Last edited:
Back
Top