Wednesday, August 7, 2013

Powershell: Open Files Matching a Search

Have I ever mentioned how much I love Powershell?

What do you do when you want to search a bunch of source files for a given string, and then open all the files that matched your search?

First you have to be able to search a bunch of files, my earlier post Powershell Grep has you covered there.  This outputs objects (a MatchInfo if you want to know) that list the files and lines that matched.  If a file had multiple matching lines, it will be listed twice, so we need to do something about that.  Then we'll need to assemble all the file paths and pass it into our favorite editor (Vim, no surprise there).

In Powershell V3 syntax the command is:
gvim (grep SearchString | group-object Path).Name
In Powershell V2 syntax you have to use ForEach-Object:
gvim (grep SearchString | group-object Path | %{ $_.Name })
If you're a programmer, especially if you're a .NET programmer, powershell is just so wonderfully intuitive (even if it is a bit verbose)!

If you develop on the Windows platform and you haven't given Powershell a look yet, you really really should.  I learned it by reading Windows Powershell In Action, a book I really enjoyed for its brevity, good examples, and awesome asides about how and why certain design decisions were made in the language.