【问题标题】:Shorten a variable long file name by strings in the front and end通过前后字符串缩短可变长文件名
【发布时间】:2020-11-11 06:52:20
【问题描述】:

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

to '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”参数调用“子字符串”的异常:“索引和长度必须引用字符串中的位置。 参数名称:长度"

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

【问题讨论】:

    标签: powershell substring


    【解决方案1】:

    您最好使用-replace operator 来提取感兴趣的子字符串:

    $baseName = '210 8th Waverly Updated Submittal (#26 0100-15.0 260100-015.00 - Short Circuit & Protective Device Coordination Study (For Rushing Review))'
    
    ($baseName -replace '^.+#([^(]+).+$', '$1').TrimEnd()
    

    以上收益
    26·0100-15.0·260100-015.00·-·Short·Circuit·&·Protective·Device·Coordination·Study,
    正如预期的那样。

    在您的命令上下文中:

    Get-ChildItem c:\*Rushing*.txt | Rename-Item -NewName { 
      ($_.BaseName -replace '^.+#([^(]+).+$', '$1').TrimEnd() + $_.Extension
    }
    

    【讨论】:

      【解决方案2】:

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

      使用与开头的 # 和结尾的 (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]
      

      Regexr link for character-by-character breakdown

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-07
        • 2018-10-12
        • 1970-01-01
        • 2017-11-11
        相关资源
        最近更新 更多