Reputation: 3
I'm trying to replace an email address string in multiple files to a new value, but I keep getting ONLY the new email address on the line, without what comes before and after the replacement string. Any ideas?
Param(
[string]$path = ".\Downloads\Backups",
[string]$filespec = "*.config",
[regex]$regex = '^(.*)(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b)(.*)$'
)
[string]$replacement = "${1}[email protected]${3}"
Get-ChildItem $path -Include $filespec -Recurse |
ForEach {
if (Get-Content $_.FullName | Select-String -Pattern $regex) {
(Get-Content $_ | ForEach {$_ -replace $regex, $replacement}) |
Set-Content $_
}
}
The initial file looks like this:
add key="EmailSubject" value="Urgent: Original Document FTP Process Errors on server" add key="Email Address" value="[email protected]" add key="SenderAddress" value="mail.mycompany.com"
The output looks like this:
add key="EmailSubject" value="Urgent: Original Document FTP Process Errors on server" [email protected] add key="SenderAddress" value="mail.mycompany.com"
Upvotes: 0
Views: 42
Reputation: 1192
From the example provided, your regex matches the entire string, and thus replaces the entire string.
Change this (https://regex101.com/r/Z84zDL/1)
[regex]$regex = '^(.*)(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b)(.*)$'
to this (https://regex101.com/r/vg4LIz/3)
[regex]$regex = '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b(.*)$'
Upvotes: 1