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



我有一个文件,其中我需要修改一个URL,但不知道该URL包含什么,就像下面的例子一样:在file.txt文件中,我必须替换URL,这样无论它是";https://SomeDomain/Release/SomeText"或";https://SomeDomain/Staging/SomeText"至";https://SomeDomain/Deploy/SomeText"。所以,无论在SomeDomain和SomeText之间写什么,都应该用一个已知的String替换。有什么正则表达式可以帮助我实现这一点吗?

我过去常常用下面的命令";

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

谢谢!

您可以使用regex-replace来完成此操作,在这里您可以捕获要保留的部分,并使用backreferences来重新创建新的字符串

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

Regex详细信息:

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

相关内容

  • 没有找到相关文章

最新更新