Hint: be aware of using Get-Content | .... | Set-Content
to the same file due to possible data loss! It doesn't apply to reading file in a subexpression/grouping expression as you did, but be aware of it in the future (as a best practice). Credits to @Ansgar Wiechers for clarification.
Solution:
You can define callback function to [Regex]::Replace (String, String, MatchEvaluator)
method:
$global:counter = 0
$content = (Get-Content c:\temp\test.txt)
# Below can be used to verify it's working correctly instead of creating a file
# $content = "aXYZ","bXYZ","cXYZ","dXYZ","eXYZ"
$content | % {[Regex]::Replace($_, 'XYZ', {return $global:counter += 1}) } | Set-Content c:\temp\test.txt
Output will be:
a1
b2
c3
d4
e5
Explanation:
The parameters you pass to Replace
are as follows:
- The string to search for a match.
- The regular expression pattern to match.
- A custom method that examines each match and returns either the original matched string or a replacement string.
The custom method increments the counter each time the regex is matched. Unfortunately, for some reason, it requires you to use global variable scope which is in general not the best practice if not needed (as mentioned by @Paxz in the comments).
As @TessellatingHeckler found out, the first version of solution used Replace
on $content
variable which resulted in removing all newlines. You have to use Foreach-Object
(or %
as its alias) to do the replacing in each single line.