Batch file help - Comparing filenames

Kelemvor

Lifer
May 23, 2002
16,928
8
81
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.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
You can set cnt using the syntax you show, but to take its value I believe you need the &#37; delimeters, i.e.

set /a cnt = %cnt% + 1
 

MerlinRML

Senior member
Sep 9, 2005
207
0
71
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 &#37;%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: