Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

powershell - Switch strings in a file

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. there will be a message box popup saying that value has been changed to [xxxxx] then background picture will be also changed accordingly.

$path = c:workest.xml
$A = AAAAA
$B = BBBBB
$settings = get-content $path
$settings | % { $_.replace($A, $B) } | set-content $path

I could not figured out how to use IF A then replace with B or IF B then replace A. Also, the code above will delete rest of contents in the file and only save the part that I modified back to the file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

$path = 'c:workest.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:workest.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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...