Use Powershell to replace subsection of regex result

前端 未结 3 1309
说谎
说谎 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:04

    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.

    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
  • 2020-12-28 16:27

    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
    }
    
    0 讨论(0)
提交回复
热议问题