grep is a robust textual content looking out utility on Linux, but it surely isn’t obtainable on Home windows. Whereas there are third occasion ports and options, PowerShell presents built-in equivalents to
grep that may do the identical job in your scripts.
Utilizing findstr to grep Search In PowerShell
There are a pair totally different search utilities in PowerShell, every with their very own strengths. The only is
findstr, which is a local home windows executable. This works nicely to exchange grep for easy search operations on the command line. For instance, you may pipe the output of
ls to it to seek out matches.
ls | findstr "foo"
You may as well seek for a number of phrases at a time, use wildcards to match something, and use the
/R flag to cross primary common expressions.
ls | findstr /R ba[a-z].txt
Although, if you wish to explicitly search together with an area, you’ll want to make use of the
ls | findstr /C:"foo"
If you happen to’re used to the Linux command line, and don’t need to keep in mind a brand new command, you may configure “grep” to be an alias to
findstr, which can allow you to preserve your muscle reminiscence.
new-alias grep findstr
Utilizing Choose-String to grep Search in PowerShell
The opposite native methodology PowerShell presents is the
Choose-String cmdlet, which does quite a lot of the identical issues as
findstr, however is a PowerShell cmdlet as a substitute of a Home windows executable.
This implies it’ll work higher in PowerShell scripts, and most notably returns its output as an object, which could be pretty-printed by PowerShell. It’s additionally simpler to make use of on the command line, as PowerShell’s tab completion will work with it.
It really works similar to
findstr, and might take wildcards and common expressions as nicely.
ls | Choose-String foo
ls | Choose-String -Sample <regexPattern>
You should use
Choose-String to grep textual content inside information, by passing it a
-Path argument. You may as well use it with enter handed from different cmdlets like
Choose-String -Path ".foo.txt" -Sample ba.*
If you happen to’d like to make use of it on the command line, you too can alias it to “grep” for fast entry.
remove-alias grep new-alias grep Choose-String