如何使用 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+/)[^/]+(/.*)', "`$1$newText`$2" | 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)
)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用Powershell从字符串中删除文本的一部分?

如何在Replace()语句中将列名用作字符串模式和替换字符串的一部分?

使用PowerShell循环搜索并在文件上替换字符串的两部分,同时保留其中一部分

使用php preg_replace替换整个字符串,如果字符串是较长字符串的一部分,则不替换

从 Powershell 中 Get-Item 的输出中获取字符串的一部分

如何使用regexp_replace删除从第一个非数字字符开始的字符串的最后一部分

Java:将字符串转换为在 url 中使用作为 get 的一部分

在特定字符串保留部分字符串以在 SQL 中替换后,如何仅替换字符串的一部分?

如何使用正则表达式选择字符串的一部分并将其放入 Powershell 中的变量中

如何使用replace语句替换1000行字段值的一部分

如何使用数组替换字符串的一部分

如何使用javascript regexp替换字符串的一部分

如何使用通配符在mysql中删除/替换字符串的一部分?

Powershell Get-Content -> 参数“-replace”

如何用字符替换字符串的一部分

如何替换字符串的一部分

如何用锚替换字符串的一部分

如何用附加条件替换字符串的一部分

如何从替换中排除匹配字符串的一部分?

如何在PHP中替换字符串的一部分?

如何按位置替换字符串的一部分?

如何在javascript中替换字符串的一部分

如何动态替换字符串的最后一部分?

如何替换pandas.Dataframe中字符串的一部分?

如何只替换单词的一部分?从字符串中提取整数?

如何用字符串数组替换句子的一部分?

Mysql:如何替换字符串的一部分?

如何用React组件多次替换字符串的一部分?

如何用sed替换多行字符串的一部分