gpt4 book ai didi

powershell - XML文件中的条件替换

转载 作者:行者123 更新时间:2023-12-03 00:47:50 24 4
gpt4 key购买 nike

我正在使用PowerShell递归替换XML文件中的文本。该脚本可以很好地替换。但是,XML文件还具有不应替换的文件路径。这是当前正在使用的脚本

if ( $content -match ' web site | web-site ' ) {
$content -replace ' web site ',' New Site ' -replace ' web-site ',' New Site ' |
Out-File $file.FullName -Encoding utf8

例如,如果XML文件具有

<title>web site</title>
<subtitle>web-site</subtitle>
<path>c:/web site/website.xml</path>

预期的输出应如下所示。文件路径中的匹配文本应被忽略。如果字符串在 /web site//web-site.xml之间,如何添加条件以忽略字符串?

<title>New Site</title>
<subtitle>New Site</subtitle>
<path>c:/web site/website.xml</path>

最佳答案

这是快速修复,但是请注意是一个更强大的解决方案,它将使用PowerShell的XML解析功能:请参阅Ansgar Wiecher's helpful answer:

注意:
-此答案假定目标字符串与XML文档的语法元素(例如元素名称和属性名称(碰巧适用于所讨论的特定字符串))不冲突,这说明了为什么使用真正的XML解析器是更好的选择。

$content = @'
<doc>
<title>web site</title>
<subtitle>web-site</subtitle>
<path>c:/web site/website.xml</path>
</doc>
'@

$modifiedContent = $content -replace '(^|[^/])web[ -]site([^/]|$)', '$1New Site$2'
# Replace 'web site' and 'web-site' if not preceded or followed by a '/'.
# Note: `web[ -]site` is the equivalent of `web site|web-site`

if ($modifiedContent -cne $content) { # If contents have changed, save.
Out-File -InputObject $modifiedContent $file.FullName -Encoding utf8
}

关于powershell - XML文件中的条件替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38534986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com