1

I want to search in files, recursively, with a pattern for the filename, for a given string, in a Windows 7 command prompt. I am familiar with Unix. So far,

findstr /spin /c:"main" *.py

is a good replacement for

find . -name "*.py" -exec grep -nH "main" {} \;

Now, if I want to show some context for each matched line (some lines before and after), how would I do that? The Unix command is

find . -name "*.py" -exec grep -nH -B 2 -A 2 "main" {} \;

As of now, I used MinGW, and I guess UnxUtils, GnuWin32, etc. may work, but I am looking for a native Windows command or sequence/pipe of commands.

EDIT: There is already one good answer posted, which gives a continuous, single-colored output. As a spun-off question, is there any way of colorizing the first line of the sequence reported for each find, so one can readily distinguish each sequence? Can the info about file/line no. be also colorized? It would be good to have something configurable in the profile (e.g., by greping ">"), so the same command given in the solution gives an output with colors. Powershell: Properly coloring Get-Childitem output once and for all is probably relevant...

0

1 Answer 1

4

Windows 7 has Powershell already installed.

for Powershell command line

WIN+R powershell

then from the powershell command prompt you can try something like

gci -r -fi '*.py' | Select-String -patt "main" -context 2,3

where gci is Get-ChildItem -r or -recurse for recursive -fi or -filter for the matching files *.py -patt or pattern for matching string "main" -co or -context 2,3 for 2 lines before 3 after

lines output with the greater than symbol at start indicate the matching lines

----------------EDIT BELOW--------------------

Tidied up to make output more readable & with colour for file and context line.

gci -r -fi '*.py'| Select-String -pattern "main" -context 2,3 | foreach { "";
$padlength = (”{0}       ” -f $_.LineNumber).Length
$pad = ” “*$padlength
$drawlength = (”{0}{1}: ” -f $_.Path, $_.LineNumber).Length
$draw = "-"*$drawlength
$(""| foreach {$_.Trim().Insert(0,$draw)});"";""
Write-Host -Fore Blue $_.Path; "";""
$($_.Context.PreContext | foreach {$_.Trim().Insert(0,$pad)})
Write-Host -Fore Magenta $(”LINE {0}: {1}” -f $_.LineNumber, ($_.Line).Trim())
$($_.Context.PostContext | foreach {$_.Trim().Insert(0,$pad)})
"";""}

referenced from: http://msmvps.com/blogs/richardsiddaway/archive/2013/01.aspx

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .