Switch strings in a file

后端 未结 2 704
春和景丽
春和景丽 2020-11-30 14:29

I have a string needs to be changed in a file between two values. What I want to do is if I found value A then change to value B, if I found value B then change to value A.

2条回答
  •  时光取名叫无心
    2020-11-30 15:33

    Assuming that $A and $B contain just simple strings rather than regular expressions you could use a switch statement with wildcard matches:

    $path = 'c:\work\test.xml'
    $A = 'AAAAA'
    $B = 'BBBBB'
    
    (Get-Content $path) | % {
      switch -wildcard ($_) {
        "*$A*"  { $_ -replace [regex]::Escape($A), $B }
        "*$B*"  { $_ -replace [regex]::Escape($B), $A }
        default { $_ }
      }
    } | Set-Content $path
    

    The [regex]::Escape() makes sure that characters having a special meaing in regular expressions are escaped, so the values are replaced as literal strings.

    If you're aiming for something a little more advanced, you could use a regular expression replacement with a callback function:

    $path = 'c:\work\test.xml'
    $A = 'AAAAA'
    $B = 'BBBBB'
    
    $rep = @{
      $A = $B
      $B = $A
    }
    
    $callback = { $rep[$args[0].Groups[1].Value] }
    
    $re = [regex]("({0}|{1})" -f [regex]::Escape($A), [regex]::Escape($B))
    
    (Get-Content $path) | % {
      $re.Replace($_, $callback)
    } | Set-Content $path
    

提交回复
热议问题