批处理脚本操作文本文件

Batch scripting manipulate text file

所以我有这段代码可以读取一个文本文件,找到字符串并将其放在另一个文本文件中,它可以正常工作。但我的问题是文本文件中有多个字符串 TEST1,但我只需要获取至少 1 行 TEST1。提前谢谢你我真的坚持这个。

@echo off
findstr /l "TEST1" *.txt > TEST1samp.txt
if %errorlevel%==0 (
echo Found!
) else (
echo No matches found
)

@echo off
findstr /l "TEST2" *.txt > TEST2samp.txt
if %errorlevel%==0 (
echo Found!
) else (
echo No matches found
)

@echo off
findstr /l "TEST3" *.txt > TEST3samp.txt
if %errorlevel%==0 (
echo Found!
) else (
echo No matches found
)

语言困难是你说你想要 at least 1 line of TEST1 这意味着你想要 1 行或更多行,但你也抱怨 there's a multiple string TEST1 in the textfile 这就是你的代码会产生的 - 不止一行行。

如果你只想要一行,那么说"I want just one line containing the target string to be written to the result file"会更清楚 - 否则,我们有无穷无尽的一系列修改来解决灰色区域。

@ECHO OFF
SETLOCAL
SET "reportfilename=newfile.txt"
SET targetstring=28180521

DEL "%reportfilename%" >NUL 2>nul
FOR /f "delims=" %%a IN ('findstr /l "%targetstring%" *.bat') DO >"%reportfilename%" ECHO %%a&GOTO done
:done
IF EXIST "%reportfilename%" (ECHO %targetstring% found) ELSE (ECHO %targetstring% NOT found)

:: change targetstring without having it explicitly in the batchfile & try again

SET /a targetstring +=1
DEL "%reportfilename%" >NUL 2>nul
FOR /f "delims=" %%a IN ('findstr /l "%targetstring%" *.bat') DO >"%reportfilename%" ECHO %%a&GOTO done2
:done2
IF EXIST "%reportfilename%" (ECHO %targetstring% found) ELSE (ECHO %targetstring% NOT found)

GOTO :eof

此过程在 *.bat 文件中测试字符串“28180521”,然后测试字符串“28180522”,产生不同的结果,因为第一个将存在于第一种情况中,但不存在于第二种情况中。但是,如果存在,它将只包含一行。