首页 > 解决方案 > Delete files based on partial names in a text file

问题描述

I would like to delete all .mp3 files in C:\temp which start with that defined witin a txt file,Mytxtfile.txt.

For example, C:\temp contains:

AliciaEffort.mp3
AliciaKlay.mp3
AliciaLow.mp3
Emanlw.mp3
EmanDown.mp3
JonKLa.mp3
JohnHd.mp3

Mytxtfile.txt contains:

AliciaEffor
Emoanlw
GrezyK
JohnHd
etc.

My code:

set WORKDIR="C:\temp"
set LISTFILES="C:\Users\StevenRg\Desktop\mytxtfile.txt"
pushd %WORKDIR%
    for %%G in (*) do (
        for /f "tokens=* usebackq" %%H in (%LISTFILES%) do (
            if %%G==%%H del /p "%%G"
             )
  )
popd

But it doesnt work ... Any ideas ?

标签: batch-file

解决方案


You could probably do it like this:

@Echo Off
Set "WorkDir=C:\temp"
Set "ListFile=%UserProfile%\Desktop\mytxtfile.txt"

CD /D "%WorkDir%" 2>Nul || Exit /B
If Not Exist "%ListFile%" Exit /B

For /F "UseBackQ Delims=" %%A In ("%ListFile%") Do Del /A /F /Q "%%A*.mp3" 2>Nul

Optionally, it may be safer to replace the last line with this:

For /F Delims^=^ EOL^= %%A In ('Type "%ListFile%"') Do Del /A /F /Q "%%~A*.mp3" 2>Nul

推荐阅读