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.

Syntax:

Select-String
      [-Culture <String>]
      [-Pattern] <String[]>
      [-Path] <String[]>
      [-SimpleMatch]
      [-CaseSensitive]
      [-Quiet]
      [-List]
      [-NoEmphasis]
      [-Include <String[]>]
      [-Exclude <String[]>]
      [-NotMatch]
      [-AllMatches]
      [-Encoding <Encoding>]
      [-Context <Int32[]>]
      [<CommonParameters>]

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) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. 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