Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing to simulate "grep -C 2" in PowerShell version 1.0

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"?

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

like image 745
slipsec Avatar asked Feb 05 '09 19:02

slipsec


4 Answers

The PowerShell equivalent of grep is select-string. You can use the following.

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

Note: this works in PowerShell v2.0 only.

like image 62
Scott Weinstein Avatar answered Nov 17 '22 13:11

Scott Weinstein


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.

like image 35
EdgeVB Avatar answered Nov 17 '22 13:11

EdgeVB


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.

like image 38
zdan Avatar answered Nov 17 '22 14:11

zdan


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.

like image 1
slipsec Avatar answered Nov 17 '22 13:11

slipsec