Switch strings in a file

后端 未结 2 705
春和景丽
春和景丽 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:15

    This isn't tested extensively, but I think it should work:

    path = c:\work\test.xml
    $A = 'AAAAA'
    $B = 'BBBBB'
    
    [regex]$regex = "$A|$B"
    
    $text = 
    Get-Content $path | 
    foreach {
    $regex.Replace($text,{if ($args[0].value -eq $A){$B} else {$A}})
    }
    
    $text | Set-Content $path
    

    Hard to be sure without knowing exactly what the data looks like.

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