I want to make grep
case insensitive by applying a default option -i
to grep
. The standard way in PowerShell is to use a function:
function grep {
env grep -i $args
}
Grep
also accepts text to search via standard input ( cat file | grep search
).
A simple way to achieve that is:
function grep($search) {
$input | env grep -i $search
Can I combine these two so that function grep
knows it was called in a pipeline? Or is there an even simpler way?
I'm going to assume that env grep
means that you have a Unix -ish environment with a grep.exe
somewhere. The proper way of wrappting that in a function that can handle parameter and pipeline input looks somewhat like this:
function grep {
[CmdletBinding(DefaultParameterSetName='content')]
Param(
[Parameter(Position=0,Mandatory=$true)]
[string]$Search,
[Parameter(
ParameterSetName='content',
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true
)]
[string]$InputObject,
[Parameter(
ParameterSetName='file',
Position=1,
Mandatory=$true
)]
[string[]]$File
)
Begin {
$grep = & env grep
}
Process {
if ($PSCmdlet.ParameterSetName -eq 'file') {
& $grep -i $Search $File
} else {
$InputObject | & $grep -i $Search
}
}
}
I finally figured it out. This might only work interactively and not in a script - because of $input
- but aliasing is generally considered an interactive technique (although providing standard options to commands not necessarily).
In this example I'm using ag
- the Silver Searcher - as it's case insensitive (actually "case-smart"), recursive and enables color by default. It searches the current directory if no path is given (which is the first "test case" to show that the function is working as intended)
function ag {
if ($input.Count) {
$input.Reset()
$input | env ag -i $args
}
else {
env ag --depth -1 --hidden --skip-vcs-ignores $args
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.