Use Powershell to replace subsection of regex result Use Powershell to replace subsection of regex result powershell powershell

Use Powershell to replace subsection of regex result


You need to group the sub-expressions you want to preserve (i.e. put them between parentheses) and then reference the groups via the variables $1 and $2 in the replacement string. Try something like this:

$regexA = '( TEST=[A-Za-z]+)14(\d\d)$'Get-ChildItem '*.txt' | ForEach-Object {    $c = (Get-Content $_.FullName) -replace $regexA, '${1}16$2' -join "`r`n"    [IO.File]::WriteAllText($_.FullName, $c)}


Here's an example using a scriptblock delegate (sometimes called an evaluator):

$regex = [regex]'( TEST=\D+)14(\d{2})\s*$'$evaluator = { '{0}16{1}' -f $args[0].Groups[1..2] }filter set-number { $regex.Replace($_, $evaluator) }foreach ($file in Get-ChildItem  "*.txt") {   ($file | get-content) | set-number | Set-Content $file.FullName }

It's arguably more complex than the -replace operator, but lets you use powershell operators to construct the replacement text, so you can do anything you can put in a script block.


Try this:

Get-ChildItem  "*.txt" |Foreach-Object {  $c = $_ | Get-Content | Foreach {$_ -replace '(?<=TEST=\D+)14(?=\d{2}(\D+|$))','16'}  $c | Out-File $_.FullName -Enc Ascii}