batch script - read line by line

前端 未结 4 1936
醉话见心
醉话见心 2020-11-29 02:48

I have a log file which I need to read in, line by line and pipe the line to a next loop.

Firstly I grep the logfile for the \"main\" word (like \"error\") in a sep

相关标签:
4条回答
  • 2020-11-29 03:13

    Try this:

    @echo off
    for /f "tokens=*" %%a in (input.txt) do (
      echo line=%%a
    )
    pause
    

    because of the tokens=* everything is captured into %a

    edit: to reply to your comment, you would have to do that this way:

    @echo off
    for /f "tokens=*" %%a in (input.txt) do call :processline %%a
    
    pause
    goto :eof
    
    :processline
    echo line=%*
    
    goto :eof
    
    :eof
    

    Because of the spaces, you can't use %1, because that would only contain the part until the first space. And because the line contains quotes, you can also not use :processline "%%a" in combination with %~1. So you need to use %* which gets %1 %2 %3 ..., so the whole line.

    0 讨论(0)
  • 2020-11-29 03:17

    For those with spaces in the path, you are going to want something like this: n.b. It expands out to an absolute path, rather than relative, so if your running directory path has spaces in, these count too.

    set SOURCE=path\with spaces\to\my.log
    FOR /F "usebackq delims=" %%A IN ("%SOURCE%") DO (
        ECHO %%A
    )
    

    To explain:

    (path\with spaces\to\my.log)
    

    Will not parse, because spaces. If it becomes:

    ("path\with spaces\to\my.log")
    

    It will be handled as a string rather than a file path.

    "usebackq delims=" 
    

    See docs will allow the path to be used as a path (thanks to Stephan).

    0 讨论(0)
  • 2020-11-29 03:30

    The "call" solution has some problems.

    It fails with many different contents, as the parameters of a CALL are parsed twice by the parser.
    These lines will produce more or less strange problems

    one
    two%222
    three & 333
    four=444
    five"555"555"
    six"&666
    seven!777^!
    the next line is empty
    
    the end
    

    Therefore you shouldn't use the value of %%a with a call, better move it to a variable and then call a function with only the name of the variable.

    @echo off
    SETLOCAL DisableDelayedExpansion
    FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
        set "myVar=%%a"
        call :processLine myVar
    )
    goto :eof
    
    :processLine
    SETLOCAL EnableDelayedExpansion
    set "line=!%1!"
    set "line=!line:*:=!"
    echo(!line!
    ENDLOCAL
    goto :eof
    
    0 讨论(0)
  • 2020-11-29 03:32

    This has worked for me in the past and it will even expand environment variables in the file if it can.

    for /F "delims=" %%a in (LogName.txt) do (
         echo %%a>>MyDestination.txt
    )
    
    0 讨论(0)
提交回复
热议问题