1

I need a bat to delete all files with the RELATIVE name contained in a text file

In the files directory the files are named like:

1_a.jpg
1_b.jpg
1_c.jpg
2_a.jpg
3_a.jpg
3_b.jpg

In the file list to delete the RELATIVE name is

2
3

I want to delete all files contains 2 and 3 (specified in file list)

After deletion remain in my folder these files (bacause not contain 2 or 3)

1_a.jpg
1_b.jpg
1_c.jpg

I tryed a batch files but i need to reverse it because this bat do not remove the files specified in text list

@echo off
setlocal
set folder="c:\somePath"
set excludeFile="c:\somePath2\someFile.txt"
for /f "eol=: delims=" %%F in ('dir /b /a-d %folder% ^| findstr /vibg:%excludeFile%') do del "%folder%\%%F"

Can you help me please?

Here there are the code to reverse to delete the files only in text list.

Is it possible for a batch file to delete a file if not found in list from text file?

Community
  • 1
  • 1
placidomaio
  • 111
  • 1
  • 13

2 Answers2

1
for /f "usebackq delims=" %%a in ("file.txt") do echo del "*%%a*"

For each element in the file, delete files containing the indicated text in its name.

The del commands are only echoed to console. If the output is correct, remove the echo.

MC ND
  • 69,615
  • 8
  • 84
  • 126
  • Hi how can i set the path folder contains the files to delete ? – placidomaio May 04 '15 at 16:33
  • @placidomaio, you can use `del "c:\somewhere\*%%a*"` or, if you have the folder in a variable, `del "%folder%\*%%a*"`, or you can, before the `for` command, use a `cd` or a `pushd` to change the current active directory – MC ND May 04 '15 at 16:35
  • Your solution works, it's possibile to add a prevent check control to prevent to delete inexistent files ? if I have in text list a words and do not exist a specified files ? Example if in list i add 9 there are not a file with name contains 9. – placidomaio May 04 '15 at 16:51
  • @placidomaio, `if exist "c:\somewhere\*%%a*" del "c:\somewhere\*%%a*"`, or simply forget about check and hide the "error" message with `del "c:\somewhere\*%%a*" 2>nul ` (the same works for the rest of the options in previous comments) – MC ND May 04 '15 at 17:40
  • Thanks your solution working like a charm, many thanks you are a great coder. Have a nice day and thanks again :) – placidomaio May 06 '15 at 10:47
0

Where LIST is the name of the file with the "2" and "3"

pushd %folder%
for /f %%a in (%LIST%) do @del %%a_*.jpg
popd

To delete all but those files, first make a list of the files that match, then using the FOR you had, delete everything else:

set folder=C:\somepath\subdir
set LIST=C:\somepath\list.txt
set excludeFile=C:\somepath\tmp.txt
if exist %excludeFile% del %excludeFile%

for /f %%a in (%LIST%) do (
    dir %%a_*.jpg > nul && dir /b %%a_*.jpg >> %excludeFile%
)

for /f "eol=: delims=" %%F in ('dir /b /a-d %folder% ^| findstr /vibg:%excludeFile%') do del "%folder%\%%F"
joeking
  • 2,006
  • 18
  • 29