使用Powershell替换文件中的多个字符串

时间:2019-01-10 13:09:02

标签: powershell replace find

我们要用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

只要id=...仅有1个实例,当文件包含多个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 

2 个答案:

答案 0 :(得分:0)

我认为这可以做到:

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

(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)
)

答案 1 :(得分:0)

您想要的是捕获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.