Alexei
Alexei

Reputation: 15674

Windows: findstr - how to print 3 lines before and after matched lines?

In Windows 7, If I want to find some text in a file, I use the following command.

findstr "find_this" trace.log

this prints all lines that contains text "find_this". OK. But I need to print also 3 lines before and 3 line after mached lines. How I can do this by command findstr?

On Unix I can do this by "grep"

 grep -B 3 -A 3 find_this trace.log

But how I can do this on Windows?

Upvotes: 39

Views: 51836

Answers (4)

Charles Miller
Charles Miller

Reputation: 11

For whoever runs into this on google, you can do this - for instance, find the line # of the thing you want, then print the lines with numbers adjacent to the one you want

@echo off 
setlocal
setlocal enabledelayedexpansion

set linesbefore=3
set linesafter=5
for /f "usebackq delims=:" %%a in (`%~1 ^| findstr /N /I "%2"`) do (
        
        echo found text @ line:%%a
        for /f "usebackq tokens=1,* delims=[]" %%b in (`%~1 ^| find /N /V ""`) do (
            set /a "firstline=%%a-%linesbefore%"
            set /a "lastline=%%a+%linesafter%"
            
            if %%b GEQ !firstline! ( if %%b LEQ !lastline! (
                if %%b EQU %%a (echo -  %%c) else (echo :   %%c)
            ))
        )
    )

example of using this batch file

Upvotes: 1

FrankT335
FrankT335

Reputation: 31

This worked for me in the windows command line:

powershell Select-String -Path "trace.log" -Pattern "find_this" -Context 3,3

Example

'Context 3,3' means to display 3 lines above and 3 lines below

Upvotes: 2

golimar
golimar

Reputation: 2548

You can use grep on Windows in a number of ways, ordered by ascending overkill-ness:

Upvotes: 1

blackpen
blackpen

Reputation: 2424

If you are open for a command in Powershell (since you seem to on Win7), ..

PS C:\Users\user> Get-Content data.txt
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve

PS C:\Users\user> Get-Content data.txt | Select-String -Pattern four -Context 2,4

  two
  three
> four
  five
  six
  seven
  eight

The Get-Content command gets the the file specified. The Select-String command takes a pattern that you want to find. The Context command let's you specify how many lines (before/after) that you want to be shown (around the line that it matched).

Upvotes: 39

Related Questions