Powershell 将文件路径中最后两次出现的“/”替换为“.”

Powershell replace last two occurrences of a '/' in file path with '.'

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

所以,转这个:

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

进入这个:

xxx-xxx-xx\xxxxxxx\x\xxxx-xxxxx-xxxx.xxxxx.xxxxx

我尝试使用替换 cmdlet 来实现这一点,但这似乎更侧重于替换所有事件或 first/last 事件,这不是我的问题。任何指导将不胜感激!

编辑:

所以,我有一个 excel 文件,我正在创建一个 powershell 脚本,该脚本在每一行上使用 for each 循环,这相当于数千个条目。对于这些条目中的每一个,我想创建一个将采用完整路径的辅助变量,并保存该路径减去最后两个斜杠。这是我正在处理的脚本部分:

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

我才刚刚开始理解正则表达式,我相信括号之间的捕获组应该至少捕获其中一个“\”,但测试尝试显示添加替换+正则表达式后没有任何变化。

如果我能提供更多信息,请告诉我。

谢谢!

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

# 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-only -split 的优雅解决方案,该解决方案具有 negative 索引(仅将固定数量的令牌从结束) 在.

试试这个

$str='xxx-xxx-xx\xxxxxxx\x\{xxxx-xxxxx-xxxx}\xxxxx\xxxxx'

#remove  bracket and split for get array
$Array=$str -replace '[{}]' -split '\'

#take all element except 2 last elements, and concat after last elems
"{0}.{1}.{2}" -f ($Array[0..($Array.Length -3)] -join '\'), $Array[-2], $Array[-1]

您可以通过两个非常简单的 -replace 操作来完成此操作:

  • 删除 {}
  • 替换最后两个\:
$str = 'xxx-xxx-xx\xxxxxxx\x\{xxxx-xxxxx-xxxx}\xxxxx\xxxxx'
$str -replace '[{}]' -replace '\([^\]*)\([^\]*)$','..'

第二个模式匹配:

\         # 1 literal '\'
(          # open first capture group
  [^\]*   # 0 or more non-'\' characters
)          # close first capture group
\         # 1 literal '\'
(          # open second capture group
  [^\]*   # 0 or more non-'\' characters
)          # close second capture group
$          # end of string

我们将其替换为第一个和第二个捕获组值,但之前使用 .,而不是 \..


如果您使用的是 PowerShell Core 版本 6.1 或更高版本,您还可以利用从右到左 -split:

($str -replace '[{}]' -split '\',-3) -join '.'

-split '\',-3-split '\',3效果一样,只是从右边拆分,而不是从左边拆分。