批处理脚本操作文本文件

时间:2015-01-27 21:38:56

标签: batch-file scripting

所以我有这个代码读取文本文件,找到字符串并将其放在另一个文本文件上,它正在工作。但我的问题是文本文件中有多个字符串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
)

1 个答案:

答案 0 :(得分:0)

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

如果你只需要一行,那么更清楚地说"我只想将一行包含目标字符串的行写入结果文件" - 否则,我们会有一系列无法​​修改以解决灰色区域。

@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

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