views:

789

answers:

5

I'm trying to dig through some logs and need information before and after the line I can match on. How would I do this in powershell ala "grep -C 2"?

Edit: in version 1 --I can't wait for r2, then I get to put it on production machines :)

+1  A: 

Alas, it looks like you will have to build it yourself or wait for the next version of powershell, as it seems to have been implemented there. You can download a pre-release version of Powershell 2.0 from here.

zdan
+1  A: 

The powershell equivlent of grep is select-string, you can use the following

cat file | select-string "pattern" -context 2

note: this works in Powershell v2 only

Scott Weinstein
v2 :@. I can't wait until I'm allowed to put it on production servers.
slipsec
+1  A: 

Getting closer here- because Select-String returns MatchInfo objects which I can pull a line number out of (39017), now I just need to pull the line surrounding... so:

gc $bigfile | Select-String melissao | 
%{(gc $bigfile)[($_.LineNumber -2)..($_.LineNumber +2)]}

If anyone could clean this up a bit to make it less slow, you may have the answer. Otherwise, this solution works but obviously not quickly.

slipsec
A: 

Download grep for Windows, and call grep from PowerShell?

Peter Seale
+2  A: 

Instead of using (gc $bigfile) again, which will cause PowerShell to read in $bigfile to memory on every object piped to it by the ForEach-Object cmdlet, you should probably read the file into a variable and then array index from that, like so:

$bigfile = gc 'c:\scripts\bigfile.txt'
$bigfile | Select-String "melissao" | % {$bigfile[($_.LineNumber -3)..($_.LineNumber +1)]}

Also, since the line numbering starts at 1 and array indexing starts at 0 you'll have to go backwards by 3, not 2, to get the line two spaces above "melissao", and go forwards by 1, not 2, to get the line two spaces below "melissao." Doing this will net you the 5 lines you want, "melissao" flanked by the two lines above and below it.

I'm not super familiar with grep -C 2, so I don't know if this replicates that functionality exactly.

EdgeVB
have an upvote- good "stop being lazy" points there :)
slipsec