Skip to content

Instantly share code, notes, and snippets.

@achembarpu
Last active February 1, 2017 07:59
Show Gist options
  • Save achembarpu/05df6e054b73d8517e9ba4f379fc40ae to your computer and use it in GitHub Desktop.
Save achembarpu/05df6e054b73d8517e9ba4f379fc40ae to your computer and use it in GitHub Desktop.
A simple powershell clone of the unix `grep` command
function Select-StringAdvanced {
Param (
[Parameter(Mandatory=$True)][string]$Pattern,
[Alias("f")][string[]]$Files,
[Alias("a")][int]$AfterContext = 0,
[Alias("b")][int]$BeforeContext = 0,
[Alias("x")][int]$Context = 0,
[string[]]$Include,
[string[]]$Exclude,
[Alias("c")][switch]$Count = $False,
[Alias("e")][switch]$ExtendedRegexp = $False,
[Alias("i")][switch]$IgnoreCase = $False,
[Alias("v")][switch]$InvertMatch = $False,
[Alias("q")][switch]$Quiet = $False,
[Parameter(ValueFromPipeline)]$Input
)
$SSArgs = @{
"Pattern" = $Pattern
"SimpleMatch" = !$ExtendedRegexp
"CaseSensitive" = !$IgnoreCase
"NotMatch" = $InvertMatch
"Quiet" = $Quiet
}
If ($Context) {
$SSArgs.Context = $Context
} Else {
$SSArgs.Context = $BeforeContext,$AfterContext
}
If ($Files) {
$SSArgs.Path = $Files
If ($Include) {
$SSArgs.Include = $Include
}
If ($Exclude) {
$SSArgs.Exclude = $Exclude
}
Select-String @SSArgs
} Else {
$Input | Select-String @SSArgs
}
}; Set-Alias grep Select-StringAdvanced
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment