切换文件中的字符串 [英] Switch strings in a file

查看:33
本文介绍了切换文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串需要在文件中的两个值之间进行更改.我想要做的是如果我找到值A然后更改为值B,如果我找到值B则更改为值A.会弹出一个消息框说值已更改为[xxxxx]然后背景图片将是也相应地发生了变化.

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:\work\test.xml
$A = AAAAA
$B = BBBBB
$settings = get-content $path
$settings | % { $_.replace($A, $B) } | set-content $path

我不知道如何使用 IF A 然后替换为 B 或 IF B 然后替换 A.此外,上面的代码将删除其余内容文件,只将我修改的部分保存回文件.

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.

推荐答案

假设 $A$B 只包含简单的字符串而不是正则表达式,您可以使用switch 带有通配符匹配的语句:

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

[regex]::Escape() 确保在正则表达式中具有特殊含义的字符被转义,因此这些值被替换为文字字符串.

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

这篇关于切换文件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆