【发布时间】:2020-03-28 09:52:55
【问题描述】:
我编辑 XML 文件并使用 PowerShell 在记事本中打开它们并替换文本字符串。给定两个不同的分隔符,开始和停止,在 XML 文件中出现 多次,我想完全删除分隔符之间的文本(分隔符是否也被删除并不重要给我)。
在下面的示例文本中,我想完全删除开始和结束分隔符之间的文本,但保留它之前和之后的所有文本。
我面临的问题是,每行文本的末尾都有 换行符,这使我无法进行简单的操作:
-replace "<!--A6-->.*?<!--A6 end-->", "KEVIN"
起始分隔符:
<!--A6-->
停止分隔符:
<!--A6 end-->
示例文本:
<listItem>
<para>Apple iPhone 6</para>
</listItem>
<listItem>
<para>Apple iPhone 8</para>
</listItem>
<!--A6-->
<listItem>
<para>Apple iPhone X</para>
</listItem>
<!--A6 end-->
</randomList></para>
</levelledPara>
<levelledPara>
<!--A6-->
<title>Available Apple iPhone Colors</title>
<para>The current iPhone model is available in
the follow colors. You can purchase this model
in store, or online.</para>
<!--A6 end-->
<para>If the color option that you want is out
of stock, you can find them at the following
website link.</para>
当前代码:
$Directory = "C:\Users\hellokevin\Desktop\PSTest"
$FindBook = "Book"
$ReplaceBook = "Novel"
$FindBike = "Bike"
$ReplaceBike = "Bicycle"
Get-ChildItem -Path $Directory -Recurse |
Select-Object -Expand FullName|
ForEach-Object {
(Get-Content $_) -replace $FindBook,$ReplaceBook -replace "<!--A6-->.*?<!--A6 end-->", "KEVIN" |
Set-Content ($_ + "_new.xml")
}
任何帮助将不胜感激。作为 PowerShell 的新手,我不知道如何在代码中的每一行末尾考虑换行符。感谢收看!
【问题讨论】:
-
做最明智的方式
<!--A6-->[\S\s]*?<!--A6 end-->
标签: regex xml powershell replace