How to grep Search Text From PowerShell

Estimated read time 2 min read


Powershell logo

grep is a powerful text searching utility on Linux, but it isn’t available on Windows. While there are third party ports and solutions, PowerShell offers built-in equivalents to grep that will do the same job in your scripts.

Using findstr to grep Search In PowerShell

There are a couple different search utilities in PowerShell, each with their own strengths. The simplest is findstr, which is a native windows executable. This works well to replace grep for simple search operations at the command line. For example, you can pipe the output of ls to it to find matches.

ls | findstr "foo"

You can also search for multiple words at a time, use wildcards to match anything, and use the /R flag to pass basic regular expressions.

ls | findstr /R ba[a-z]\.txt

Though, if you want to explicitly search including a space, you’ll need to use the /C: flag:

ls | findstr /C:"foo"

If you’re used to the Linux command line, and don’t want to remember a new command, you can configure “grep” to be an alias to findstr, which will let you keep your muscle memory.

new-alias grep findstr

Using Select-String to grep Search in PowerShell

The other native method PowerShell offers is the Select-String cmdlet, which does a lot of the same things as findstr, but is a PowerShell cmdlet instead of a Windows executable.

This means it will work better in PowerShell scripts, and most notably returns its output as an object, which can be pretty-printed by PowerShell. It’s also easier to use on the command line, as PowerShell’s tab completion will work with it.

It works just like findstr, and can take wildcards and regular expressions as well.

ls | Select-String foo
ls | Select-String -Pattern <regexPattern>

You can use Select-String to grep text inside files, by passing it a -Path argument. You can also use it with input passed from other cmdlets like Get-Content.

Select-String -Path ".\foo.txt" -Pattern ba.*

If you’d like to use it at the command line, you can also alias it to “grep” for quick access.

remove-alias grep
new-alias grep Select-String





Source link

You May Also Like

More From Author