Home > Software engineering >  Batch file to delete specific files in multiple folders
Batch file to delete specific files in multiple folders

Time:02-09

I need to delete specific files from 28 folders on the same server. e.g

C:/folder/DMP/app_x0

C:/folder/DMP/app_x1

C:/folder/DMP/app_x2

DeleteList.txt has a list of files names (with path).

C:/folder/DMP/app_x0/ABC1.txt

C:/folder/DMP/app_x0/ABC1.doc

The batch file needs to have a loop to go through each folder one by one and delete all files mentioned in a text file. Following worked ok for one folder only if I specify the full path before each file's names in DeleteList.txt file.

for /f "delims=" %%f in (DeleteList.txt) do del "%%f"

How to use above so that same code could run 28 times in batch file but each time replaces folder location path. DeleteList.txt will not change.

Any sample code/suggestion would help. Thx.

CodePudding user response:

One of these questions where we need to read between the lines.

Given we have on file of full filenames with the incorrect path separator, and a requirement to delete the files from 28 directories (but there's no list) then I conclude that since the required subdirectories shown are all subdirectories of C:\folder\DMP\ then the requirement actually is to delete all of the files that match the filenames in the file in all subdirectories of the parent directory of the full filename in the list.

So my suggestion would be

 for /f "delims=" %%b in (DeleteList.txt) do del /s "%%~dpb..\%%~nxb"

Naturally, you should test this on a dummy tree before implementing it.

del /s deletes in the target directory and all subdirectories. The target subdirectory is the drive and path of %%b; its parent (..); the name and extension part of %%b.

I prefer to use metavariables that are not available as metavariable-modifiers.

To delete in subdirectories but not in the parent:

for /f "delims=" %%b in (DeleteList.txt) do FOR /d %%c IN ("%%~dpb..\*") DO del /s "%%c\%%~nxb">nul

This time, %%c is set to all subdirectorynames in turn, and the del/s applied to each subdirectory. The /s (...and subdirectories) probably isn't required. The >nul suppresses the deletion report if desired.

  •  Tags:  
  • Related