我正在尝试将多个文件中的电子邮件地址字符串替换为一个新值,但是我一直只获得该行上的新电子邮件地址,而替换字符串之前和之后都没有。 有什么想法吗?
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}newemail@mycompany.com${3}"
Get-ChildItem $path -Include $filespec -Recurse |
ForEach {
if (Get-Content $_.FullName | Select-String -Pattern $regex) {
(Get-Content $_ | ForEach {$_ -replace $regex, $replacement}) |
Set-Content $_
}
}
初始文件如下:
add key="EmailSubject" value="Urgent: Original Document FTP Process Errors on server" add key="Email Address" value="myaddress@mycompany.com" add key="SenderAddress" value="mail.mycompany.com"
输出看起来像这样:
add key="EmailSubject" value="Urgent: Original Document FTP Process Errors on server" newemail@mycompany.com add key="SenderAddress" value="mail.mycompany.com"
答案 0 :(得分:1)
在提供的示例中,您的正则表达式匹配整个字符串,从而替换了整个字符串。
更改此(https://regex101.com/r/Z84zDL/1)
[regex]$regex = '^(.*)(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b)(.*)$'
对此(https://regex101.com/r/vg4LIz/3)
[regex]$regex = '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b(.*)$'