Powershell replace multiple occurrences of regex in text file

Viewed 367

I have a huge file with the index of a book and I need to subtract 2 to all numbers. Each line may have more numbers like:

Surname, Name 12, 17-33
Second, Name 75

and I need them to become

Surname, Name 10, 15-31
Second, Name 73

I have written this small script using references around in order to do the task:

`$trova = "[0-9]+(?![^<>]*>)"
(Get-Content D:\path\document.xml) |
Foreach-Object {if ($_ -match "$trova"){
$cambia= $matches[0]
$cambia-=2
$_ -replace $trova, $cambia}
} | 
Set-Content D:\path\document2.xml`

The problem is that I can only successfully match the first one of each line, than all the substitution are with the same number, thus

Surname, Name 10, 10-10
Second, Name 73

I'm a bit stuck. I have seen some suggestion to use

Select-String $trova -input $string -AllMatches

but I cannot see how to properly make it work in order to do the math before doing the substitution. The file is the xml from a docx document (I need to retain the style) but I decided to work directly from powershell instead of using the Word.Application because it seemed easier (this is why my regex avoid the numbers inside a tag). Thanks for any suggestion.

0 Answers
Related