How to write -replace in powershell where number follows sequence
For example, let's say I want to take a string Hello World
and use -replace
"World1" to output. This was my attempt at expressing:
"Hello World" -replace '.*(World)','$11'
But the problem here is that it sees $ 11 as the 11th sequence, not $ 1 and then 1. I tried to find an escape character to indicate that I want 1 after $ 1 but couldn't find anything.
The real world problem I was trying to solve was to collect a bunch of email addresses and create aliases with a number at the end. for example
jsmith@example.com
becomes
jsmith1@example.com jsmith2@example.com
+3
source to share
2 answers
try this:
$Email = "jsmith@example.com"
$Domain = ($Email -split "@")[-1]
for ($i=1;$i -le 5;$i++)
{
(($Email -split "@")[0] + $i),$Domain -join "@"
}
## Result
jsmith1@example.com
jsmith2@example.com
jsmith3@example.com
jsmith4@example.com
jsmith5@example.com
If you don't need that, you can avoid the for loop and just replace $ i in this section:
$Email -split "@")[0] + $i
+1
source to share