Skip to Content

How do I find and replace text in a file in PowerShell?

PowerShell provides several ways to find and replace text in files. This can be useful for tasks like renaming variables, updating configuration values, modifying code, and more.

In PowerShell, we can use cmdlets like Select-String to find text, and Get-Content/Set-Content to read and write file contents. We can also use regular expressions for powerful pattern matching and replacement capabilities.

Here are some common methods for finding and replacing text in files with PowerShell:

Using Select-String to Find Text

The Select-String cmdlet can search for text in files or input strings. It’s useful for finding text patterns and checking if a file contains specific words or phrases.

Here’s the basic syntax for Select-String:

“`powershell
Select-String -Pattern -Path
“`

The -Pattern parameter specifies the text pattern to match. The -Path parameter points to the file to search.

For example, to search for “Windows” in a text file:

“`powershell
Select-String -Pattern “Windows” -Path C:\Users\admin\data.txt
“`

This will print any line containing the word “Windows” from that file.

We can also use the -SimpleMatch switch to find exact matches instead of regex patterns:

“`powershell
Select-String -Pattern “Windows” -Path C:\Users\admin\data.txt -SimpleMatch
“`

Some other useful parameters include:

– -CaseSensitive – Match case exactly
– -Quiet – Hide output, just return match boolean
– -List – Print only the matched lines
– -Encoding – Specify file encoding
– -AllMatches – Return all matches, not just first

So Select-String provides a quick way to check if a file contains some text we need to find or replace.

Reading and Writing File Contents

To actually replace text in a file, we need to read its contents into memory, perform the replacement, then write the changes back to the file.

PowerShell provides easy file I/O with Get-Content and Set-Content.

Get-Content reads a file and returns its contents as a string array:

“`powershell
$fileContents = Get-Content -Path C:\Users\admin\data.txt
“`

We can then modify the array with our text replacements.

Set-Content writes the string array back to the file, overwriting it:

“`powershell
Set-Content -Path C:\Users\admin\data.txt -Value $fileContents
“`

So the basic workflow is:

1. Get-Content to read the file into a variable
2. Modify the array with replacements
3. Set-Content to write the changes back

This allows simple find and replace operations.

Replacing Text with String Methods

For basic text replacement, we can use built-in .NET string methods like Replace():

“`powershell
$fileContents = Get-Content -Path C:\Users\admin\data.txt

$fileContents -replace “Windows”, “Linux”

Set-Content -Path C:\Users\admin\data.txt -Value $fileContents
“`

Here we:

1. Get the file contents
2. Use -replace to substitue “Windows” with “Linux”
3. Write the modified content back to the file

This does a basic search and replace.

Other useful string methods include:

– Replace(oldValue, newValue) – Replace specific text
– ToLower() / ToUpper() – Change case
– Trim() – Remove leading/trailing whitespace
– Split() / Join() – Split and join strings

These give us flexibility to transform text before writing it back to the file.

Using Regular Expressions

For more complex find and replace scenarios, PowerShell supports regular expressions with the -match and -replace operators.

Regular expressions give us wildcards, quantifiers, anchors, and other advanced patterns for matching text:

“`powershell
# Match email addresses
[email protected]” -match “^\w+@\w+\.\w+$”

# Replace decimal numbers with fractions
“2.5” -replace “(.+)\.”, ‘$1 1/’
“`

Here are some common regex features:

– . – Wildcard, matches any character
– \w – Word character (letter, number, underscore)
– \d – Digit
– \s – Whitespace
– * – Zero or more matches
– + – One or more matches
– ? – Optional match
– {n} – Exactly n matches
– ^ and $ – Start and end anchors
– | – Logical OR
– (…) – Groups for backreferences like $1, $2

So with regular expressions, we can search for complex patterns and make powerful replacements.

To use regex for file find/replace:

“`powershell
$fileContents = Get-Content file.txt
$fileContents -replace “regex”, “replacement”
Set-Content file.txt $fileContents
“`

This allows us to modify text based on patterns, not just direct matches.

Finding and Replacing in Bulk Files

So far, we’ve seen how to find and replace text in a single file. To do this across many files, we can wrap the logic in a PowerShell loop like ForEach-Object:

“`powershell
Get-ChildItem -Path C:\Users\Admin\Documents -Filter *.txt |
ForEach-Object {
$content = Get-Content $_
$content -replace “Windows”, “Linux” | Set-Content $_
}
“`

This loops through all .txt files, reads each one, performs the replace, then writes the changes back to the file.

The Get-ChildItem cmdlet retrieves the files using the -Filter parameter. We pipe those into ForEach-Object, which loops through each file object represented by $_.

Inside the script block, we get the content, do the replace, then output with Set-Content back to the file ($_).

This gives us a simple way to bulk process text replacement across multiple files.

Finding and Highlighting Text Matches

Sometimes you may just want to find and highlight matches instead of replacing text.

For example, you could search for important keywords and highlight them in a document.

To highlight matches, we can use the built-in .NET Regex class in PowerShell:

“`powershell
$content = Get-Content -Path C:\Users\Admin\document.txt

$highlight = [regex]::Matches($content, “keyword”, “RightToLeft”) |
ForEach-Object { $_.Value.Insert(0, ““).Insert($_.Length+3,”“) }

$highlight -join ”;
“`

This inserts HTML bold tags around matched keywords to highlight them.

The key points are:

– Use [regex]::Matches to find all matches
– ForEach-Object to wrap each match in bold tags
– Join the results back together

Now $highlight contains the document text with highlighted keywords!

You could write this back to a file, output to the console in color, or display in a UI like PowerShell ISE for highlighting.

Replacing Text in Binary Files

The file techniques work well for plain text files.

Binary files like Office documents, PDFs, JPEGs, etc require different handling.

In these cases, we need to extract the text with the appropriate encoding, then write the modified text back into the binary format.

Here’s an example for DOC/DOCX Word files using the Word.Application COM object:

“`powershell
$word = New-Object -ComObject Word.Application
$word.Visible = $false # Run in background

$docPath = “C:\Users\Admin\document.docx”

# Open document
$doc = $word.Documents.Open($docPath)

# Extract text
$docText = $doc.Content.Text

# Replace text
$docText -replace “Windows”, “Linux” | Out-String | %{ $_ -replace “`r`n”, ” ” } > $tempFile

# Update document text
$doc.Content.Text = Get-Content $tempFile

# Save and close
$doc.Save()
$doc.Close()
“`

Here we:

– Open Word and the DOCX document
– Extract the text content into a string
– Perform text replace on the string
– Write the modified text to a temp file
– Set the updated text back into the Word document
– Save and close Word

This allows us to modify text in the binary DOCX format.

The same concept applies for other formats like PDF, Excel spreadsheets, etc – extract the text, replace, then import back.

Finding and Replacing Text in Code Files

When working with code like PowerShell scripts, JavaScript, JSON, CSV, etc, we may want to do code-specific find and replace.

For example, safely renaming a variable or function name across an entire codebase.

To handle code:

– Use Abstract Syntax Tree (AST) parsers to safely modify code structure
– Preserve code formatting and style
– Update references to renamed elements

PowerShell has AST parsers for JSON (ConvertFrom-Json) and CSV (Import-Csv).

For other languages, we can use advanced AST libraries like PSParsedHtml for HTML, PSScriptAnalyzer for PowerShell, and more.

Here’s an example with JSON using the ConvertFrom-Json AST:

“`powershell
$json = Get-Content -Raw .\config.json | ConvertFrom-Json

$json.settings.theme = “light”
$json.security.apiKey = “new123”

$json | ConvertTo-Json -Depth 100 | Set-Content -Path .\config.json
“`

This safely modifies JSON structure while preserving formatting, spaces, etc.

For PowerShell code specifically, PSScriptAnalyzer can rewrite scripts with Rename-Script:

“`powershell
Rename-Script -Path .\script.ps1 -Rename *oldvar*,*newvar*
“`

So using language-specific parsers gives us safe code modification capabilities.

Finding and Replacing Across Projects

For large projects and codebases, manually finding and replacing text is inefficient.

Some better approaches:

– Use regex searches across the whole project
– Integrate with source control like git to track changes
– Take advantage of editor/IDE find-replace tools

PowerShell regex search across a project:

“`powershell
# Recursively find all PS1 files
Get-ChildItem .\project -Recurse -Filter *.ps1 |

# Search the content of each
ForEach-Object {
$content = Get-Content $_
if($content -match “SomePattern”) {
# Found a match – do something

$content # Show matching line
}
}
“`

Here we recursively traverse the whole project directory, search each .ps1 file, and output any matches.

We could also pipe the results to Set-Content to replace text in matches.

For source control, tools like git provide powerful search and diffs for changes:

“`bash
# Search across all files for a pattern
git grep “SomePattern”

# See changes about to be committed
git diff –staged

git log -p # Search history of changes
“`

IDEs like VSCode also have robust find/replace across projects and files.

So combining OS-level PowerShell search with source control and editor integration gives a full-featured cross-project search and replace capability.

Conclusion

In summary, here are some effective ways to find and replace text in files with PowerShell:

– Use Select-String to search and find pattern matches
– Read contents with Get-Content, modify text, then write back with Set-Content
– Leverage string methods like Replace(), regex -match and -replace
– Loop through files recursively with Get-ChildItem and ForEach-Object
– Extract and re-import text for binary formats like Word, PDF
– Use AST parsers to safely modify structured code
– Search across projects with regex and integrate with git, IDEs

Finding and replacing text is a common task that PowerShell is well-suited for. With its strong string processing and file handling capabilities, both simple and complex text modifications are straightforward.

Example Scripts

Here are some full PowerShell scripts demonstrating file find and replace techniques:

Basic String Replace

“`powershell
# Read file contents
$files = Get-ChildItem *.txt

foreach ($file in $files) {

$content = Get-Content $file.FullName

# Replace text
$newContent = $content -replace ‘find’, ‘replace’

# Write back to file
Set-Content -Path $file.FullName -Value $newContent
}
“`

Regex Replace

“`powershell
Get-ChildItem *.* -Recurse | ForEach-Object {

$content = Get-Content $_

# Use regex
$newContent = $content -replace ‘\d{3}-\d{3}-\d{4}’, ‘XXX-XXX-XXXX’

Set-Content $_ $newContent
}
“`

Bulk Rename Files

“`powershell
Get-ChildItem *.txt | ForEach-Object {

# Extract name
$name = $_.BaseName

# Append string
$newName = $name + “-append”

# Rename file
Rename-Item -Path $_.FullName -NewName ($newName + ‘.txt’)
}
“`

Highlight Keywords

“`powershell
$content = Get-Content .\document.txt

$highlight = [regex]::Matches($content, “keyword”, “RightToLeft”) |
ForEach-Object { $_.Value.Insert(0, ““).Insert($_.Length+3, ““) }

$highlight -join ” | Set-Content highlight.txt
“`

So in summary, PowerShell provides very flexible options for finding and replacing text in files, to handle both simple and complex scenarios. The key is understanding the range of string manipulation, regex, and file I/O capabilities available.