Use Powershell to replace subsection of regex result

前端 未结 3 1322
说谎
说谎 2020-12-28 15:51

Using Powershell, I know how to search a file for a complicated string using a regex, and replace that with some fixed value, as in the following snippet:

Ge         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-28 16:08

    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)
    }
    

提交回复
热议问题