首页 > 解决方案 > 通过前后字符串缩短可变长文件名

问题描述

我想从“ 210 8th Waverly Updated Submittal (#26 0100-15.0 260100-015.00 - Short Circuit & Protective Device Coordination Study (For Rushing Review)).txt中缩短这个文件名

至“ 26 0100-15.0 260100-015.00 - 短路和保护装置协调研究.txt

我使用井号 (#) 来剪裁正面,并使用文本“(For Rushing Review)”剪裁结尾。

Get-ChildItem 'c:\*Rushing*.txt' | Rename-Item -NewName {$_.BaseName.substring($_.BaseName.lastindexof('(#') + 15, $_.BaseName.IndexOf('(For Rushing Review)')-$_.BaseName.lastindexof('(#') + 15)+$_.Extension }

但我收到错误 Rename-Item : 参数“NewName”的脚本块输入失败。使用“2”参数调用“子字符串”的异常:“索引和长度必须引用字符串中的位置。参数名称:长度”

由于文件名的可变长度,我需要在子字符串的末尾使用一个变量。

标签: powershellsubstring

解决方案


正则表达式非常适合这种字符串解析。

在开始时使用与 # 相同的逻辑,最后使用 (For Rushing Review) 的相同逻辑,我将新文件名和扩展名设置为两个捕获组。

$Original = '210 8th Waverly Updated Submittal (#26 0100-15.0 260100-015.00 - Short Circuit & Proctective Device Coordination Study (For Rushing Review)).txt'
$Pattern = '^.+\(#(.+) \(For Rushing Review\).*(\..+)$'

$Original -Match $Pattern
$Matches[1]+$Matches[2]

用于逐个字符细分的正则表达式链接


推荐阅读