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



我想逐行读取文件,并将该行与数据中的用户键进行比较。如果键入的数据与整行的至少一个单词匹配,my-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等不必要的输出?

下面是代码+文本文件+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"x网络。存在。5846">

Set_Param_10A"TRUE"x网络.存在。7425"Set_Param_1 0A"TRUE"xnetwork.existent.1420"Set_Param_10A"TRUE"xnetwwork.existent.0632"Set_Param_10A"TRUE"网络存在。1112"Set_Param_1 0A"TRUE"xnetwork.existent.8524"Set_Param_10A"TRUE"xnetwwork.existent.3675"Set_Param_10A"TRUE"x网络.存在。3344"Set_Param_1 0A"TRUE(真("xnetwork.existent.1276"Set_Param_10A"TRUE"xnetwwork.existent.4796"Set_Param_10A"TRUE"网络.存在。3349"Set_Param_1 0A"TRUE"xnetwork.existent.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已忽略

@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...再次输出

第二种方法要容易得多。。。

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

... do call match_function %%G

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

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

最新更新