powershell - Powershell将文件路径中最后出现的 '/'替换为 '.'

标签 powershell powershell-4.0

我有一个文件路径,我试图将/字符的最后两次出现删除为.,并通过Powershell完全删除“{}”,然后将其转换为变量。

所以,打开这个:

xxx-xxx-xx\xxxxxxx\x\{xxxx-xxxxx-xxxx}\xxxxx\xxxxx

变成这个:
xxx-xxx-xx\xxxxxxx\x\xxxx-xxxxx-xxxx.xxxxx.xxxxx

我已经尝试使用replace cmdlet来解决这个问题,但这似乎更着重于替换所有出现的情况或第一次出现/最后出现的情况,这不是我的问题。任何指导将不胜感激!

编辑:

因此,我有一个excel文件,我正在创建一个powershell脚本,该脚本在每行上的每个循环中都使用a,这等于数千个条目。对于每个条目,我想创建一个辅助变量,该变量将使用完整路径,并保存该路径减去最后两个斜杠。这是我正在处理的脚本部分:
Foreach($script in $roboSource)
   {
    $logFileName = "$($script.a).txt".Replace('(?<=^[^\]+-[^\]+)-','.')
   } 

$ script.a将以这种格式输出数千个条目:
xxx-xxx-xx \ xxxxxxx \ x {xxxx-xxxxx-xxxx} \ xxxxx \ xxxxx
这是预期的。

我想要$ logFileName输出:
xxx-xxx-xx \ xxxxxxx \ x \ xxxx-xxxxx-xxxx.xxxxx.xxxxx

我刚刚开始了解正则表达式,并且我相信括号之间的捕获组应该捕获至少一个'\',但是在添加replace + regex之后的测试尝试未显示任何变化。

请让我知道是否可以提供更多信息。

谢谢!

最佳答案

在这种情况下,两步方法最简单:

# Input string.
$str = 'xxx-xxx-xx\xxxxxxx\x\{xxxx-xxxxx-xxxx}\xxxxx\xxxxx'

# Get everything before the "{"
$prefix = $str -replace '\{.+'

# Get everything starting with the "{", remove "{ and "}", 
# and replace "\" with "."
$suffix = $str.Substring($prefix.Length) -replace '[{}]' -replace '\\', '.'

# Output the combined result (or assign to $logFileName)
$prefix + $suffix

如果您想通过一个-replace操作(带有嵌套)来完成此操作,事情就会变得更加复杂:

注意:此解决方案需要PowerShell Core(v6.1 +)
$str -replace '(.+)\{(.+)\}(.+)',
  { $_.Groups[1].Value + $_.Groups[2].Value + ($_.Groups[3].Value -replace '\\', '.') }

另请参阅基于优雅的仅PS-Core的-split的解决方案,在Mathias R. Jessen's helpful answer中带有负索引(仅从末端拆分固定数量的 token )。

关于powershell - Powershell将文件路径中最后出现的 '/'替换为 '.',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58843384/

相关文章:

powershell - 如何在Powershell中基于主机名将设备对象过滤为单个对象?

azure - 使用 powershell 获取 Cosmosdb 容器集合项目

arrays - 扩展哈希表中的属性

powershell - Powershell 中的 PsObject 数组

powershell - 使用 Invoke-Command 格式化输出

regex - 使用大括号和关键字之间的 RegEx 获取内容

有关排序和管道的 PowerShell 问题

powershell - Import-Module 仅在从 Get-Module 进行管道传输时才有效

c# - 我可以在我托管的 PowerShell 中创建变量并启动我的类的方法吗?

powershell - 为什么 PowerShell ISE 中的控制台不使用最新安装的 PowerShell 版本?