grep for PowerShell

The unix grep command is always handy.  So I decided to make a PowerShell function that can recursively search through files and return the results with the search term highlighted.

function mgrep ([string] $search, [string] $include=”*”, [string] $path=”.”, [switch] $noRecurse=$false, [switch] $caseSensitive=$false)
{
 get-ChildItem -recurse:(-not $noRecurse) -force -include $include -path $path |
  Where-Object { $_ -is [System.IO.FileInfo] } |
   select-String -caseSensitive:$caseSensitive $search |
    format-table -p Filename, Linenumber, @{ Label = “Snippet”; Expression={$_.Line.Trim()}} -groupby path -autosize |
     Out-String -stream |
      foreach {
       $ct = 0
       $regExOptions = “None”
       if(-not $caseSensitive) { $regExOptions = “IgnoreCase” }
       $parts = [regex]::split($_,$search, $regExOptions);
       foreach ($part in $parts) {
        Write-host -nonewline $part
        
        if(++$ct -lt $parts.Length)
        {
         Write-Host -nonewline -foregroundcolor yellow $search
        }
       }
       Write-Host “”
       $str = “”
      }
}

Examples:

“find the word ‘fundemental’ in all files recursing subdirectories and ignoring case”
mgrep fundemental  

“find the work ‘elaborate’ in files ending in TXT, do not recurse and match case”

mgrep elaborate *.txt -caseSensitive -noRecurse
-or-
mgrep elaborate *.txt -c -n

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s