Delete all files in a folder but skip files that cointain certain string

江枫思渺然 提交于 2020-06-29 03:46:46

问题


I'm trying to clean the temp files, but I want skip some files that cointain a certain name. No matter the extension it is.

Tried this way:

@echo off
setlocal EnableDelayedExpansion
for /f "eol=: delims="  %F in ('dir "%windir%/temp" /b /a-d * ') do find "TESTE" %F > nul || del "%F"
pause

Wanted all files that cointains TESTE in name got skipped from deletation.

But my script not even run.

Can someone explain me what is wrong?


回答1:


It is not absolutely clear whether you want to exclude files from deletion whose names or whose contents include a certain string; anyway, this is for the former:

pushd "%WinDir%\TEMP" && (
    for /F "delims= eol=|" %%F in ('
        dir /B /A:-D "*.*" ^| findstr /V /I /C:"TESTE"
    ') do (
        ECHO del /F "%%F"
    )
    popd
)

Once you are satisfied with the output, remove the upper-case ECHO command.


The above script would also not delete files whose extensions contain the given string. But if you want to regard only the base name, you might want to use this code instead:

pushd "%WinDir%\TEMP" && (
    for /F "delims= eol=|" %%F in ('
        dir /B /A:-D "*.*"
    ') do (
        set "NAME=%%~nF"
        setlocal EnableDelayedExpansion
        if /I "!NAME:TESTE=!"=="!NAME!" (
            endlocal
            ECHO del /F "%%F"
        ) else endlocal
    )
    popd
)



回答2:


You should be able to use findstr.exe with its /V and /M options to list your unwanted files.

@SetLocal EnableExtensions
@For /F "Delims=" %%G In (
    '%__AppDir__%findstr.exe /VPMLI "TESTE" "%SystemRoot%\TEMP\*" 2^>NUL'
)Do @Del /A/F "%%G"
@Pause

Please note that the \Windows\Temp directory is usually protected, so you may need to run this script 'as administrator'.



来源:https://stackoverflow.com/questions/62460468/delete-all-files-in-a-folder-but-skip-files-that-cointain-certain-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!