batch script to print previous and next lines of search string in a text file

后端 未结 3 1709
孤城傲影
孤城傲影 2020-12-30 17:44

I have a batch script which will print the entire line of search string into a text file.

for %%i in (log.txt) do (
FINDSTR /G:pattern.txt %%i >> outpu         


        
相关标签:
3条回答
  • 2020-12-30 18:14

    try this:

    for /f "delims=:" %%a in ('findstr /in "error" log.txt') do set /a found=%%a
    if not defined found (echo "error" not found&goto:eof)
    set /a line1=found-1
    set /a line2=found+1
    for /f "tokens=1*delims=:" %%a in ('findstr /in "^" log.txt') do (
        if %%a==%line1% >>output.txt echo(%%b
        if %%a==%line2% >>output.txt echo(%%b
    )
    
    0 讨论(0)
  • 2020-12-30 18:17
    @echo off
    setlocal EnableDelayedExpansion
    rem Assemble the list of line numbers
    set numbers=
    for /F "delims=:" %%a in ('findstr /I /N /C:"error occurred" log.txt') do (
       set /A before=%%a-1, after=%%a+1
       set "numbers=!numbers!!before!: !after!: "
    )
    rem Search for the lines
    (for /F "tokens=1* delims=:" %%a in ('findstr /N "^" log.txt ^| findstr /B "%numbers%"') do echo %%b) > output.txt
    
    0 讨论(0)
  • 2020-12-30 18:19

    This uses a helper batch file called findrepl.bat from - http://www.dostips.com/forum/viewtopic.php?f=3&t=4697

    @echo off
    set "var=searchterm"
    type "file.txt"|findrepl "%var%" /o:-1:+1 |find /v "%var%"
    
    0 讨论(0)
提交回复
热议问题