【问题标题】:Replace multiple strings in a file with Powershell用 Powershell 替换文件中的多个字符串
【发布时间】:2019-01-10 22:11:43
【问题描述】:

我们想用特定的模式替换变量id=* 的多个实例,例如id=1234。 我已经制作了这个 Powershell 脚本(并且更喜欢继续使用 Powershell 作为解决方案):

$line = Get-Content C:\test.txt | Select-String "id=" | Select-Object -ExpandProperty Line
$content = Get-Content C:\test.txt
$content | ForEach {$_ -replace $line,"id=1234"} | Set-Content C:\test.txt
Get-Content C:\test.txt

只要只有 1 个 id=... 实例,此方法就有效,当文件包含 id=... 的多个实例时,根本不会执行替换步骤。

输入文件类似于:

text over here
id=1
text over here: id={123456}
text
id=number1
id=#3 text 
id=3+3 text 

这应该导致:

text over here
id=1234
text over here: id=1234
text
id=1234
id=1234 text 
id=1234 text 

【问题讨论】:

  • 所以替换 id= 和后面的任何字符直到行尾? (Get-Content C:\test.txt) | ForEach {$_ -replace "id=.*","id=1234"}
  • 带有positive lookbehind (gc C:\test.txt) -replace '(?<=id=)[^\s]+','1234'的变体

标签: powershell replace find


【解决方案1】:

你想要的是捕获id= 之后的每个字符,直到你碰到一个空格。

以下将正常工作

$content = Get-Content "C:test.txt" -raw
$content = $content -replace 'id=[^\s]*','id=1234'
Set-Content C:\test.txt
Get-Content C:\test.txt

使用-Raw 参数会将文件快速加载到字符串而不是数组中。 从那里,使用上面的替换,你会得到想要的结果。

[^\s]* 匹配单个字符,不包括空格字符(空格、制表符、回车、换行)

您可以在创建正则表达式语句时使用 RegexStorm。

See the regex I provided tested on there.

【讨论】:

    【解决方案2】:

    我认为这样可以:

    将文本读取为字符串数组并逐行替换:

    (Get-Content 'C:\test.txt') | 
        ForEach-Object { $_ -replace '(id\s*=\s*[^\s]+)', 'id=1234' } | 
        Add-Content -Path 'C:\test_updated.txt'
    

    或将文本作为单个字符串读取并执行多行替换 ((?m))

    (Get-Content C:\test.txt -Raw) -replace '(?m)(id\s*=\s*[^\s]+)', 'id=1234' | 
        Set-Content -Path 'C:\test_updated.txt'
    

    我强烈建议您为输出文件使用新文件名,这样您就不会覆盖原始文件。

    在这两种情况下,代码都会返回:

    text over here
    id=1234
    text over here: id=1234
    text
    id=1234
    id=1234 text 
    id=1234 text
    

    正则表达式详细信息

    (            Match the regular expression below and capture its match into backreference number 1
       id        Match the characters “id” literally
       \s        Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
          *      Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
       =         Match the character “=” literally
       \s        Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
          *      Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
       [^\s]     Match any character that is NOT a “A whitespace character (spaces, tabs, line breaks, etc.)”
          +      Between one and unlimited times, as many times as possible, giving back as needed (greedy)
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-20
      • 2015-11-07
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2017-06-23
      • 2022-07-12
      相关资源
      最近更新 更多