【问题标题】:Replace text between two string powershell替换两个字符串powershell之间的文本
【发布时间】:2019-12-25 14:32:21
【问题描述】:

我有一个问题,我一直坚持..

我有一个名为 xml_data.txt 的文件和另一个名为 entry.txt 的文件

我想替换<core:topics> and </core:topics>之间的所有内容

我写了下面的脚本

$test = Get-Content -Path ./xml_data.txt
$newtest = Get-Content -Path ./entry.txt
$pattern = "<core:topics>(.*?)</core:topics>"
$result0 = [regex]::match($test, $pattern).Groups[1].Value
$result1 = [regex]::match($newtest, $pattern).Groups[1].Value
$test -replace $result0, $result1

当我运行它输出到控制台的脚本时,它看起来并没有做出任何改变。

谁能帮帮我

注意:拼写错误已修复

【问题讨论】:

  • 使用$test = Get-Content -Path ./xml_data.txt -Raw$pattern = "(?s)&lt;core:topics&gt;(.*?)&lt;/core:topics&gt;"
  • DO NOT parse XML with regex。要操作 XML 数据,请使用 PowerShell 的内置 XML 解析器。请注意,您的数据显然正在使用 namespaces,因此您需要注意这一点。
  • $test -replace [regex]::Escape($result0), $result1
  • @WiktorStribiżew 如果我有多个条目,我将如何循环该条目
  • 对不起,我认为您的问题相当不明确,有点过于宽泛。

标签: regex powershell replace file-get-contents


【解决方案1】:

这里有三个主要问题:

  • 您逐行读取文件,但文本块是多行字符串
  • 您的正则表达式不匹配换行符,因为. 默认情况下不匹配换行符
  • 此外,当用动态替换模式替换时,文字正则表达式模式必须始终对$ 符号进行美元转义。或者使用简单的字符串.Replace

所以,你需要

  • 将整个文件读入单个变量$test = Get-Content -Path ./xml_data.txt -Raw
  • 使用$pattern = "(?s)&lt;core:topics&gt;(.*?)&lt;/core:topics&gt;" 正则表达式(可以通过将其展开到&lt;core:topics&gt;([^&lt;]*(?:&lt;(?!&lt;/?core:topics&gt;).*)*)&lt;/core:topics&gt; 来增强它以防工作太慢)
  • 使用$test -replace [regex]::Escape($result0), $result1.Replace('$', '$$') 来“保护”替换中的$ 字符,或$test.Replace($result0, $result1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-27
    • 2021-07-23
    • 1970-01-01
    • 2021-01-28
    • 2021-03-29
    • 2016-08-13
    • 2020-06-26
    • 1970-01-01
    相关资源
    最近更新 更多