Quick Tip: PowerShell Grep Equivalent

I’ve used searching in my previous PowerShell posts, but I thought that it deserves a dedicated “Quick Tip” posting.  I know that folks coming from a *nix background will be very familiar with using grep to search for pretty much anything and seemingly not having access to this tool can be disappointing for those trying to use Windows as their primary OS (for the one or two of you out there that have decided to come to the “dark side” 8-) ).  But…do not fret!  There are a number of ways to run equivalent searches within Windows out of the box.  Since I’ve been on a PowerShell kick lately, let me introduce you to a decent grep alternative that is built into PowerShell: select-string.

Select-String is a built-in cmdlet in PowerShell that will allow you to search files, piped input, objects, etc for a pattern (which is, by default, a regular expression).  Select-String can take in a number of options, but can be quite simple to use.  For example, if you want to search for the text “evildoer” within all files in the current directory, you can use the following command:

select-string .\*.* -pattern "evildoer"

It is important to note that by default, select-string is case-insensitive; so, if you need a case sensitive search, add in the -CaseSensitive parameter.

Ok, now let’s do something a bit more complex.  I want to look for anything that looks like an email address in all txt files recursively under C:\.  So, to make that happen we need to do a little more work:

get-childitem c:\ -include *.txt -rec | select-string -pattern "\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6}"

First, I need to use get-childitem (think DIR) to recursively go through the drive and return only files matching *.txt.  Then I pipe these returned objects to select-string and search their contents by using a basic regex that will match on things that look like email addresses.

Of course, there are a number of other ways to use select-string but since this is a “quick tip” I’ll keep things brief.  If you’d like more details, you can find additional information in the PowerShell documentation on TechNet.

Comments

  1. Thomas says

    One other thing to note, dir is an alias for get-childitem, and you don’t have to say -include, so your example can be shortened to

    dir c:\ *.txt -rec | select-string -pattern “\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6}”

    Plus, get-alias | where-object {$_.Definition -match “Select-String”} tells us that we can use sls instead of select-string. And we can shorten -rec to -r as well.

    dir c:\ *.txt -r | sls -pattern “\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6}”

    Thanks for the post!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>