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

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

2
  • What exactly does grep -C 2 do? Commented Feb 5, 2009 at 19:42
  • it provides Context, @JaredPar - unixhelp.ed.ac.uk/CGI/man-cgi?grep Commented Feb 5, 2009 at 19:49

5 Answers 5

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

v2 :@. I can't wait until I'm allowed to put it on production servers.
3

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.

Comments

1

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.

Comments

1

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.

Comments

0

Download grep for Windows, and call grep from PowerShell?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.