从文件中搜索文本并使用Batch获取整行

时间:2015-10-23 17:17:53

标签: windows batch-file

有没有办法使用批处理来获取特定的文本块,在txt文件中搜索它,如果找到该文本,它将采用它所在的行并将整行保存为变量? / p>

例如:

@echo off
Rem THIS IS THE BATCH FILE!
set /p op="Enter Text To Search>"
if %op%==%op% goto Search

:Search
Rem Search in text file: information.txt
Rem Find Chunk of text and line its on
Rem And after its found save the whole line as a variable!

Echo %Whole_Line%
pause
exit

示例文本文件:

Set dt=2015-10-20 Set Tm=18:05:47.47 Set Ipw=%ipwan% set loc=%location% Set Img=%ImgName%.bmp
Set dt=2015-10-21 Set Tm=06:20:10.28 Set Ipw=%ipwan% set loc=%location% Set Img=%ImgName%.bmp
Set dt=2012-01-09 Set Tm=8:09:26.31 Set Ipw=%ipwan% set loc=%location% Set Img=%ImgName%.bmp

提前致谢!

1 个答案:

答案 0 :(得分:1)

使用FINDSTR的简单FOR / F

第一次编辑:添加逻辑以找不到一行。

第二次编辑:脚本现在为它找到的每一行设置一个新的环境变量。

set "whole_line1="
FOR /F "tokens=1* delims=:" %%G IN ('findstr /C:"%op%" information.txt ^|FINDSTR /N /C:"%op%"') do set "whole_line%%~G=%%~H"
IF NOT DEFINED whole_line1 GOTO error