Batch file 用于删除文件夹中不包含特定单词的文件的批处理脚本

Batch file 用于删除文件夹中不包含特定单词的文件的批处理脚本,batch-file,scripting,textedit,Batch File,Scripting,Textedit,我不熟悉批处理脚本编写。我需要删除文件夹中中不包含某些单词的所有文件 找到了这个代码 @echo off setlocal pushd C:\Users\admin\Desktop\bat findstr /ip /c:"importantWord" *.txt > results.txt popd endlocal 那么,我如何才能将这些文件列为白名单,并删除所有其他文件? 或者我认为有一种简单的方法,只需检查!包含和删除 但我不知道怎么做?这应该可以: @ECHO OFF SETLO

我不熟悉批处理脚本编写。我需要删除文件夹中中不包含某些单词的所有文件

找到了这个代码

@echo off
setlocal
pushd C:\Users\admin\Desktop\bat
findstr /ip /c:"importantWord" *.txt > results.txt
popd
endlocal
那么,我如何才能将这些文件列为白名单,并删除所有其他文件? 或者我认为有一种简单的方法,只需检查!包含和删除 但我不知道怎么做?

这应该可以:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET "pathToFolder=C:\FolderToEmpty"
SET "wordToSearch=ImportantWord"
FOR /F "tokens=*" %%F IN ('dir %pathToFolder% /b *.txt') DO (
    findstr /IP %wordToSearch% "%pathToFolder%\%%F">nul
    IF !ERRORLEVEL!==1 (
        DEL /Q "%pathToFolder%\%%F"
    )
)

您必须设置要从中删除文件的文件夹的正确路径,并用正在查找的子字符串替换ImportantWord。

假设,可以通过非常简单的方式解决此问题,将这些
findstr
开关:/V组合在一起,在找不到搜索字符串时显示结果,和/M,仅显示文件的名称;即:

@echo off
setlocal
cd C:\Users\admin\Desktop\bat
for /F "delims=" %%a in ('findstr /ipvm /c:"importantWord" *.txt') do del "%%a"
不幸的是,/V和/M开关的组合不能正常工作:/V的结果基于行(而不是文件),因此需要对该方法进行修改:

@echo off
setlocal
cd C:\Users\admin\Desktop\bat

rem Create an array with all files
for %%a in (*.txt) do set "file[%%a]=1"

rem Remove files to preserve from the array
for /F "delims=" %%a in ('findstr /ipm /c:"importantWord" *.txt') do set "file[%%a]="

rem Delete remaining files
for /F "tokens=2 delims=[]" %%a in ('set file[') do del "%%a"
这种方法非常有效,特别是对于大文件,因为
findstr
命令只报告文件名,并在第一个字符串匹配后停止搜索

@echo off
setlocal
set "targetdir=C:\Users\admin\Desktop\bat"
pushd %targetdir%
for /f "delims=" %%a in ('dir /b /a-d *.txt') do (
 findstr /i /p /v /c:"importantWord" "%%a" >nul
 if not errorlevel 1 echo del "%%a"
)
popd
endlocal

不确定要对
/p
文件执行什么操作-对于这些文件,包含非ansi字符的文件似乎返回errorlevel
1
<代码>如果没有错误级别1将回显不包含所需字符串的文件-删除
回显
以实际删除文件

谢谢,它正在工作。我应该在哪里只指定*.txt文件?只为*.txt编辑我的答案。