Welcome to MSDN Blogs Sign in | Join | Help

Select-String and Grep

Dustin Marx has a blog entry where he compares Unix/Linux, PowerShell and DOS commands.  In it he says, "If there is one Unix command I would love to have in PowerShell, it is the grep command with its regular expression support."  Well Dustin, your wish is our command.  Select-String command to be precise:

PS> Get-Help Select-String

NAME
    Select-String

SYNOPSIS
    Identifies patterns in strings.

SYNTAX
    Select-String [-pattern] <string[]> -inputObject <psobject> [-include <stri
    ng[]>] [-exclude <string[]>] [-simpleMatch] [-caseSensitive] [-quiet] [-lis
    t] [<CommonParameters>]

    Select-String [-pattern] <string[]> [-path] <string[]> [-include <string[]>
    ] [-exclude <string[]>] [-simpleMatch] [-caseSensitive] [-quiet] [-list] [<
    CommonParameters>]

DETAILED DESCRIPTION
    Identifies patterns in strings. By default, Select-String interprets the va
    lue of the Pattern parameter as a regular expression and matches input agai
    nst it. To learn more about regular expressions in Windows PowerShell, type
     get-help about_regular_expression. You can suppress the regular expression
     match by using the SimpleMatch parameter. A simple match attempts to find
    the string specified in the Pattern parameter as a substring of the input.

    The cmdlet makes it easy to search string content from files. It includes a
     Path parameter that supports wildcards and when that parameter is used, th
    e contents of the referenced files are retrieved and matched against the va
    lue of the Pattern parameter.

    Output from the cmdlet is, by default, a MatchInfo object which includes de
    tailed information about the matches. The information is most useful when t
    he input to the cmdlet is retrieved from files. The object includes propert
    ies like Filename and Line, which have the value 'InputStream' when the inp
    ut was not from a file. You can use the Quiet parameter to suppress the out
    put of MatchInfo objects. In that case, the resulting output becomes a bool
    ean value that is true if a match occurred and false otherwise.

    When matching file content, you can use the List parameter to stop after th
    e first match in each input file. You should use this parameter if you only
     require a single match, because it will result in faster matching commands.

There are a ton of great scenarios but here are some of the more common usages:

PS> dir . -recurse |%{ "`n*** $($_.name)"; cat $_}

*** animals.txt
dog
cat
horse
cow

*** fruit.txt
orange
apple
cherry

*** trees.txt
Elm
Maple
Oak
Dogwood
Apple

PS> Set-Alias ss Select-String

PS> ss Dog *

animals.txt:1:dog
trees.txt:4:Dogwood

PS> ss Dog * -CaseSensitive

trees.txt:4:Dogwood

PS> ss ^[cd]o *

animals.txt:1:dog
animals.txt:4:cow
trees.txt:4:Dogwood

PS> ss ^[cd]o -path * -Exclude *an*.txt

trees.txt:4:Dogwood

 

We've expanded Select-String in the next version with a number of additional functions.  One of my favorites is -Context which allows you to specify the number of lines  you want displayed before and after a match.  Check it out:

PS> ss oak *

trees.txt:3:Oak

PS> ss oak * -Context 1,0

  trees.txt:2:Maple
> trees.txt:3:Oak

PS> ss oak * -Context 0,1

> trees.txt:3:Oak
  trees.txt:4:Dogwood

PS> ss oak * -Context 2,1

  trees.txt:1:Elm
  trees.txt:2:Maple
> trees.txt:3:Oak
  trees.txt:4:Dogwood

And last but not least, this is PowerShell so of course we are not going to just emit text, we emit objects which

PS> ss dog * |fl *

IgnoreCase : True
LineNumber : 1
Line       : dog
Filename   : animals.txt
Path       : C:\temp\ss\animals.txt
Pattern    : dog

IgnoreCase : True
LineNumber : 4
Line       : Dogwood
Filename   : trees.txt
Path       : C:\temp\ss\trees.txt
Pattern    : dog

We should have produced an alias from grep to Select-String.

Enjoy!

Jeffrey Snover [MSFT]
Windows Management Partner Architect
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Published Sunday, March 23, 2008 8:22 PM by PowerShellTeam

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# MSDN Blog Postings &raquo; 2008 &raquo; March &raquo; 23

Sunday, March 23, 2008 4:03 PM by MSDN Blog Postings » 2008 » March » 23

# re: Select-String and Grep

I'm looking forward to v2 of Powershell with the context option (I think that's what it is) so that I can get more than just the line that was found but also +/- a line before and after.

Also, I've seen some scripts that do highlighting (via Write-Host with a foreground color), but any chance we'll see official support for that?

Sunday, March 23, 2008 10:53 PM by David Mohundro

# re: Select-String and Grep

The best part about the emitted object is that you can get full access to the match details, match groups, etc.  Having had to do subsequent string parsing on the regex'd match, and finding out things like the string position of the regex match, or the what particular substring was matched was great!

Monday, March 24, 2008 12:56 AM by james

# @ Dave Mohundro

Dave,

The coloring you mention, via write-host, is directly built into the cmdlet, and you can use it with v1.

PSH>write-host -fore yellow -back red "hello"

Monday, March 24, 2008 10:20 AM by Marco Shaw

# re: Select-String and Grep

Jeffery,

Does that mean one could use get-content -wait and pipe that to Select-String to watch a file and trigger an event when something matches?

thanks,

mike

axel::foley

Monday, March 24, 2008 5:55 PM by mike foley

# re: Select-String and Grep

> Does that mean one could use get-content -wait and pipe that to Select-String to watch a file and trigger an event when something matches?

I have not tried that but I think you'll be able to connect those dots.  You'd need to run it in the background and then register for output events.

Jeffrey Snover [MSFT]

Windows Management Partner Architect

Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell

Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Monday, March 24, 2008 11:51 PM by PowerShellTeam

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker