使用for循环逐行读取文件并匹配DOS中所需的密钥内容

时间:2014-06-10 05:31:17

标签: batch-file for-loop findstr

我想逐行读取文件并将该行与用户键入数据进行比较。 如果键入数据与整行的至少1个字匹配,则我的dos窗口将输出该行。

任何人都可以指导我完成此代码吗?

SET user_key_in_data=abc

FOR /F "delims=" %%G IN (%~dp0database.txt) DO (CALL :match_function)

:match_function

这是我的尝试代码,但它无法正常工作:

@echo off
SETLOCAL EnableDelayedExpansion

SET matchpattern=NETWORK.*ISSUE

FOR /F "delims=" %%G IN (database.txt) DO (SET currentline=%%G & CALL :match_function)
pause
GOTO:eof

:match_function
    findstr /I /R /C %matchpattern% %currentline%
    if %errorlevel%==0 (
        echo %currentline%
    )
GOTO:eof

Stephan回复后更新:

为什么当匹配条件不符合时,DOS仍会打印出FINDSTR: /C ignored等不必要的输出?

下面是代码+ textfile + dos输出?

代码:

@echo off
SETLOCAL EnableDelayedExpansion

FOR /F "tokens=*" %%G IN (log_network.txt) DO (CALL :process %%G)
pause
GOTO:eof

:process
    echo %* | findstr /I /R /C "0632" > nul
    if %errorlevel%==0 (
        echo %*
    )
GOTO:eof

log_network.txt文件:

Set_Param_10A" TRUE" " xnetwork.exist.5846"

  

Set_Param_10A" TRUE" " xnetwork.exist.7425" Set_Param_10A" TRUE"   " xnetwork.exist.1420" Set_Param_10A" TRUE" " xnetwork.exist.0632"   Set_Param_10A" TRUE" " xnetwork.exist.1112" Set_Param_10A" TRUE"   " xnetwork.exist.8524" Set_Param_10A" TRUE" " xnetwork.exist.3675"   Set_Param_10A" TRUE" " xnetwork.exist.3344" Set_Param_10A" TRUE"   " xnetwork.exist.1276" Set_Param_10A" TRUE" " xnetwork.exist.4796"   Set_Param_10A" TRUE" " xnetwork.exist.3349" Set_Param_10A" TRUE"   " xnetwork.exist.0048"

Dos输出:

FINDSTR:/ C忽略

FINDSTR:/ C忽略

FINDSTR:/ C忽略

FINDSTR:/ C忽略

Set_Param_10A" TRUE" " xnetwirk.exist.0632"

FINDSTR:/ C忽略

FINDSTR:/ C忽略

FINDSTR:/ C忽略

FINDSTR:/ C忽略

FINDSTR:/ C忽略

FINDSTR:/ C忽略

FINDSTR:/ C忽略

FINDSTR:/ C忽略

2 个答案:

答案 0 :(得分:0)

您不需要%currentline%。只需将该行作为参数传递给子函数:

... do call match_function %%G

在子功能中,您可以将其用作%*(所有参数)

:match_function
echo %* | findstr /I /R /C %"matchpattern%" >nul
if ...

答案 1 :(得分:0)

@ECHO OFF
SETLOCAL

SET "matchpattern=NETWORK.*ISSUE"

FOR /f "delims=" %%a IN (q24133524.txt) DO (SET currentline=%%a & CALL :match_function)
ECHO(=============
FINDSTR /i /r /c:"%matchpattern%" q24133524.txt


GOTO :EOF
:match_function
    ECHO(%currentline%|findstr /I /R /C:"%matchpattern%"
    if %errorlevel%==0 (
        echo %currentline%
    )
GOTO :eof

我使用了一个名为q24133524.txt的文件,其中包含我的测试数据。

这显示了您的过程的异化版本的结果(findstr找到字符串并输出它,然后if errorlevel...再次输出它。

第二种方式更容易......