Successfully added
PowerShell
by Patrik
Normalize and Replace Identifiers in Files Using PowerShell
Sometimes configuration files or scripts include identifiers that need to be updated automatically — for example, replacing a generic keyword like "rule-template"
with a dynamic name based on a service or environment.
This Snipp shows how to:
- Replace an exact identifier in a file
- Normalize that name (e.g. replacing special characters like dots)
Goal
Replace this:
rule-template
With something like:
rule-example-service
Where "example.service"
is the dynamic input.
PowerShell Example
# Define the original dynamic name
$name = "example.service"
# Normalize the name (e.g., replace '.' with '-')
$normalizedName = $name -replace '\.', '-'
# Read the text file content
$content = Get-Content -Path "file.txt" -Raw
# Replace the exact identifier
$content = $content -replace 'rule-template', "rule-$normalizedName"
# Save the updated content
Set-Content -Path "file.txt" -Value $content
This ensures that:
- Only exact matches of
"rule-template"
are replaced - Any special characters in the name are safely converted
Summary
This method is useful when working with reusable config files across different services or environments. PowerShell makes it easy to normalize and apply names consistently, reducing manual edits and potential mistakes.
powershell
scripting
automation
text-replace
normalization
Referenced in:
Comments