PowerShell: Search Text in Files (grep)

By Xah Lee. Date: . Last updated: .

Here's ways to search a string in file content of files in a dir. (like linux grep)

Search Text by Regex, a Single File

search by Regular Expression

Select-String -Path "~/alice.txt" -Pattern 'rabbit'

🛑 WARNING: Select-String search based on lines. by default, it won't find text that span multiple lines.

Search Text that Span Multiple Lines

# search text that span multiple lines
Get-Content "~/blog.html" -raw | Select-String '(?s)<ul>.<li>'
# (?s) is regex flag. it means, make the dot to also match newline char

Search by Regex, Multiple Files

dir -recurse -file -filter *.html | Select-String "joe|jane"

〔see also List File by File Name Pattern

Search by Literal String

parameter SimpleMatch for match by literal string

dir -recurse -file -filter *.html | Select-String "alice" -SimpleMatch

Case Sensitive Search

dir -recurse -file -filter *.html | Select-String "Alice" -SimpleMatch -CaseSensitive

Search Multiple text Patterns

dir -recurse -file -filter *.html | Select-String regex1, regex2

Common Select-String parameters

-SimpleMatch

Match as literal string on value of -pattern. (by default, the -pattern is interpreted as regex)

-CaseSensitive

Case sensitive. (by default, it's case-insensitive)

-AllMatches

Find all matches in a line. (by default, only first match in a line is found.) This parameter is ignored when used in combination with the SimpleMatch parameter. To absolutely get all matches, don't use the SimpleMatch parameter. Escape your -pattern value instead. See about_Regular_Expressions.

-NotMatch

List lines that do not match.

PowerShell. List Dirs and Files

List Dirs

List Files

Create, Copy, Delete, Dir

Path Tutorial