如何使用 PowerShell Get-Content -replace 仅替换一部分字符串

How to replace only a portion of string using PowerShell Get-Content -replace

我有一个文件需要修改 URL,不知道 URL 包含什么,就像下面的例子一样: 在文件 file.txt 中,我必须将 URL 替换为“https://SomeDomain/Release/SomeText”或“https://SomeDomain/Staging/SomeText”到“https://SomeDomain/Deploy/SomeText”。因此,无论在 SomeDomain 和 SomeText 之间写入什么,都应该用已知的字符串替换。是否有任何正则表达式可以帮助我实现这一目标?

我以前是用下面的命令来做的

((Get-Content -path "file.txt" -Raw) -replace '"https://SomeDomain/Release/SomeText");','"https://SomeDomain/Staging/SomeText");') | Set-Content -Path "file.txt"

这很好用,但我必须知道在 file.txt 中 URL 是否包含 Release 或 Staging,然后才能执行命令。

谢谢!

您可以使用正则表达式 -replace 执行此操作,在其中捕获您希望保留的部分并使用反向引用重新创建新字符串

$fileName = 'Path\To\The\File.txt'
$newText  = 'BLAHBLAH'

# read the file as single multilined string
(Get-Content -Path $fileName -Raw) -replace '(https?://\w+/)[^/]+(/.*)', "`$newText`" | Set-Content -Path $fileName

正则表达式详细信息:

(              Match the regular expression below and capture its match into backreference number 1
   http        Match the characters “http” literally
   s           Match the character “s” literally
      ?        Between zero and one times, as many times as possible, giving back as needed (greedy)
   ://         Match the characters “://” literally
   \w          Match a single character that is a “word character” (letters, digits, etc.)
      +        Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   /           Match the character “/” literally
)             
[^/]           Match any character that is NOT a “/”
   +           Between one and unlimited times, as many times as possible, giving back as needed (greedy)
(              Match the regular expression below and capture its match into backreference number 2
   /           Match the character “/” literally
   .           Match any single character that is not a line break character
      *        Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)