Use Powershell to replace subsection of regex result

前端 未结 3 1328
说谎
说谎 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.

提交回复
热议问题