grepis really a powerful text searching utility on Linux, nonetheless it isnt on Windows. While you can find alternative party ports and solutions, PowerShell offers built-in equivalents to
grepwhich will do exactly the same job in your scripts.
Using findstr to grep Search In PowerShell
There are always a couple different search utilities in PowerShell, each making use of their own strengths. The easiest is
findstr, that is a native windows executable. This is effective to displace grep for simple search operations at the command line. For instance, it is possible to pipe the output of
lsto it to get matches.
ls | findstr "foo"
You can even seek out multiple words at the same time, use wildcards to complement anything, and utilize the
/Rflag to pass basic regular expressions.
ls | findstr /R ba[a-z].txt
Though, if you need to explicitly search including an area, youll have to utilize the
ls | findstr /C:"foo"
If youre used to the Linux command line, and dont desire to remember a fresh command, it is possible to configure grep to be an alias to
findstr, that may enable you to keep your muscle memory.
new-alias grep findstr
Using Select-String to grep Search in PowerShell
Another native method PowerShell offers may be the
Select-Stringcmdlet, which does most of the same things as
findstr, but is really a PowerShell cmdlet rather than a Windows executable.
This implies it will are better in PowerShell scripts, & most notably returns its output being an object, which may be pretty-printed by PowerShell. Its also better to use on the command line, as PowerShells tab completion will continue to work with it.
It works exactly like
findstr, and may take wildcards and regular expressions aswell.
ls | Select-String foo
ls |Select-String -Pattern
You may use
Select-Stringto grep text inside files, by passing it a
-Pathargument. You may also utilize it with input passed from other cmdlets like
Select-String -Path ".foo.txt" -Pattern ba.*
If youd prefer to utilize it at the command line, you may also alias it to grep for fast access.
remove-alias grep new-alias grep Select-String