Search code examples
batch-filewindows-scriptingfindstr

Returning the surrounding lines to a string windows batch file


I'm using findstr to search for a string in a file in the following manner:

findstr "test" file.txt

This is returning the line where test is found, but I would like to return the 3 lines above and below the matching line. I've had a look and it doesn't seem like there are any in-built options to findstr to return surrounding lines.


Solution

  • Here you go

    @echo off
    setlocal enabledelayedexpansion
    for /f "tokens=1 delims=:" %%a in ('findstr /n "hello" file.txt') do (
    set /a line=%%a
    )
    set /a num=0
    for /l %%b in (3,-1,1) do (
    set /a lines[!num!]=!line!-%%b
    set /a num+=1
    )
    for /l %%c in (1,1,3) do (
    set /a lines[!num!]=!line!+%%c
    set /a num+=1
    )
    set /a count=1
    for /f "tokens=* delims=" %%d in (file.txt) do (
    for /l %%e in (%lines[0]%,1,%lines[5]%) do (
    if !count!==%%e if not %%e==!line! echo %%d
    )
    set /a count+=1
    )
    pause >nul