PowerShell: Grep Command Alternative - Select-String

The grep command is the most powerful UNIX utility for searching any given input files and matching using regular expressions and patterns. If you are looking for a command that works like the grep, you can make use of the Select-String cmdlet.

The Select-String cmdlet can be found in the Microsoft.PowerShell.Utility module of PowerShell. It can be used to find text in strings and files.


      [-Culture <String>]
      [-Pattern] <String[]>
      [-Path] <String[]>
      [-Include <String[]>]
      [-Exclude <String[]>]
      [-Encoding <Encoding>]
      [-Context <Int32[]>]

Let's take a look at a few examples.

Example 1: Simple Text Matching

PS> 'Welcome to Code2care' | Select-String -Pattern 'Code2care' -SimpleMatch

Welcome to Code2care

Example 2: Simple Text Case Sensitive Matching

PS> 'Welcome to Code2care' | Select-String -Pattern 'Code2care' -SimpleMatch -CaseSensitive

Welcome to Code2care

Note: If there is no match, the prompt returns with no output.

Example 3: Find Matching Text Within a file

PS> Select-String ./file1.txt -Pattern "PowerShell"

file1.txt:2:PowerShell is fun!
PowerShell Select-Search Example - Alternative to Grep Command

Above examples are based on PowerShell Core version 7.3 on macOS.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap