slipsec
slipsec

Reputation: 3062

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 :)

Upvotes: 5

Views: 2497

Answers (5)

Scott Weinstein
Scott Weinstein

Reputation: 19117

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.

Upvotes: 8

EdgeVB
EdgeVB

Reputation: 496

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.

Upvotes: 3

slipsec
slipsec

Reputation: 3062

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.

Upvotes: 1

Peter Seale
Peter Seale

Reputation: 5025

Download grep for Windows, and call grep from PowerShell?

Upvotes: 0

zdan
zdan

Reputation: 29450

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.

Upvotes: 1

Related Questions