【问题标题】:Replace Text using powershell使用 powershell 替换文本
【发布时间】:2016-07-19 11:43:39
【问题描述】:

我有一个包含以下内容的文本文件:

some text
some text some text some text
somevariable=334,321;  
somevariable=234,234;
some text b = 34 some text some text

我想换行

somevariable=334,321;

与

somevariable=10,20;   

我可以通过以下方式做到这一点

 $content.replace("somevariable=334,321;", "somevariable=10,20;")  

但问题是我的 somevariable 可以是任何东西,我想用我的值替换它。

$content.replace("somevariable=?,?", "somevariable=10,20;")    

您能告诉我如何更新文本文件中的变量吗?

【问题讨论】:

    标签: security powershell automation


    【解决方案1】:

    使用-replace 运算符,它采用正则表达式模式作为第一个 rhs 参数:

    $content -replace '(?<=somevariable=)\d+,\d+;','10,20;'
    

    【讨论】:

    • 嗨,当我执行此错误“正则表达式模式无效”
    • @yogeshkmrsoni somevariable 的真正价值是什么?它是否包含任何特殊字符?他们需要逃跑
    • 看看这个:PS C:\Windows\system32> (gc E:\secpol.cfg) -replace '(?
    • 是的,\ 需要转义:\\.或者,仅在前瞻中搜索字符串的最后一部分:(?&lt;=LMCompatibilityLevel=)\d+,\d+;
    • @yogeshkmrsoni 只需谷歌“正则表达式”,那里有很多材料 :-) 请注意,由于 PowerShell 在 .NET 上运行,它使用与 C# 相同的正则表达式引擎/风格
    【解决方案2】:

    您可以将regex 与-replace 方法一起使用:

    $content -replace "somevariable=.*$", "somevariable=10,20;"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      • 2015-10-28
      • 1970-01-01
      • 2022-10-06
      • 2021-06-09
      • 2020-10-30
      相关资源
      最近更新 更多