Andre
Andre

Reputation: 11

Batch delete dased on file name

I have a folder that gets used for importing values from csv files into an excel spread sheet. This means that multiple times a day I need to delete and rename batches of files to work with the provided macro. I've automated the deleting and renaming, but the delete part of my batch file is more than a little clumsy, and is only coded to work with 20 files. It looks as follows:

del 1.csv
del 2.csv
etc

I'd like to loop this part of the batch file, but the only code I've found deletes based on file extension and not file name. What I'd like is to delete all single or double digit named csv files and to preserve any csv not in the same format. Any help or pointing to resources will be very much appreciated.

Upvotes: 1

Views: 317

Answers (3)

Aacini
Aacini

Reputation: 67216

To delete one-digit files:

for /L %%a in (0,1,9) do del %%a.csv

To delete two-digit files:

setlocal EnableDelayedExpansion
set number=99
for /L %%a in (1,1,100) do (
   set /A number+=1
   del !number:~-2!.csv
)

Upvotes: 1

foxidrive
foxidrive

Reputation: 41224

Try this - if it echoes the right filenames then remove the echo. It should delete CSV files with 2 or 1 character names, that are numbers.

@echo off
for /f "delims=" %%a in (' dir ??.csv /b ^|findstr /r "^[0-9]*" ') do echo del "%%a"

Upvotes: 1

Monacraft
Monacraft

Reputation: 6630

I don't completely understand but I think you're looking for the for /l command:

for /l %%a in (1,1,[number for last file]) do del %%a.csv

e.g.

for /l %%a in (1,1,10) do del %%a.csv

will delete 1.csv to 10.csv

Hope this helped

Yours, Mona

Upvotes: 1

Related Questions