通过前后字符串缩短可变长文件名
Shorten a variable long file name by strings in the front and end
我想缩短此文件名来自'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 - 短路和保护装置协调Study.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”参数调用“子字符串”的异常:“索引和长度必须引用字符串中的位置。
参数名称:长度
由于文件名的长度可变,我需要为子字符串的结尾使用一个变量。
正则表达式非常适合这种字符串解析。
在开头和结尾使用 # 的相同逻辑,我将新文件名和扩展名设置为两个捕获组。
$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]
您最好使用 来提取感兴趣的子字符串:
$baseName = '210 8th Waverly Updated Submittal (#26 0100-15.0 260100-015.00 - Short Circuit & Protective Device Coordination Study (For Rushing Review))'
($baseName -replace '^.+#([^(]+).+$', '').TrimEnd()
以上结果
26·0100-15.0·260100-015.00·-·Short·Circuit·&·Protective·Device·Coordination·Study
,
不出所料。
在您的命令上下文中:
Get-ChildItem c:\*Rushing*.txt | Rename-Item -NewName {
($_.BaseName -replace '^.+#([^(]+).+$', '').TrimEnd() + $_.Extension
}
我想缩短此文件名来自'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 - 短路和保护装置协调Study.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”参数调用“子字符串”的异常:“索引和长度必须引用字符串中的位置。 参数名称:长度
由于文件名的长度可变,我需要为子字符串的结尾使用一个变量。
正则表达式非常适合这种字符串解析。
在开头和结尾使用 # 的相同逻辑,我将新文件名和扩展名设置为两个捕获组。
$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]
您最好使用
$baseName = '210 8th Waverly Updated Submittal (#26 0100-15.0 260100-015.00 - Short Circuit & Protective Device Coordination Study (For Rushing Review))'
($baseName -replace '^.+#([^(]+).+$', '').TrimEnd()
以上结果
26·0100-15.0·260100-015.00·-·Short·Circuit·&·Protective·Device·Coordination·Study
,
不出所料。
在您的命令上下文中:
Get-ChildItem c:\*Rushing*.txt | Rename-Item -NewName {
($_.BaseName -replace '^.+#([^(]+).+$', '').TrimEnd() + $_.Extension
}