【问题标题】:Powershell - Rename filename by removing the last few charactersPowershell - 通过删除最后几个字符重命名文件名
【发布时间】:2015-10-21 09:40:54
【问题描述】:

我想删除多个文件名的最后 11 个字符。例如 我有这些文件名:

ABCDE_2015_10_20
HIJKL_2015_10_20
MNOPQ_2015_10_20
RSTUV_2015_10_20

想将它们重命名为

ABCDE
HIJKL
MNOPQ
RSTUV

我已尝试使用以下代码:

Get-ChildItem 'E:\Thomson Reuters\Stage' | rename-item -newname { [string]($_.name).substring($_.name.length -14) } 

谁能告诉我哪里出错了?

【问题讨论】:

  • 你有没有尝试过自己解决这个问题?
  • 是的 - 我可以删除文件名开头的字符,但不能使用以下命令删除最后一个字符:Get-ChildItem 'E:\Thomson Reuters\Stage' |重命名项目 -newname { [string]($_.name).substring($_.name.length -14) }
  • edit这个问题并用你到目前为止写的代码更新它

标签: powershell


【解决方案1】:

你就快到了,你只需要告诉substring确切的开始和结束位置:

Get-ChildItem 'E:\Thomson Reuters\Stage' | rename-item -newname { $_.name.substring(0,$_.name.length-11) } 

通过将两个整数传递给substring,您可以为其指定要捕获的字符串的 StartIndex 和 Length。 See here 用于文档

【讨论】:

    【解决方案2】:

    只是为了补充来自arco444的回复:

    Get-ChildItem 'E:\Thomson Reuters\Stage' -filter *.txt | rename-item -NewName {$_.name.substring(0,$_.BaseName.length-6) + $_.Extension -replace "_"," "}
    

    这将重命名目录中的所有 .txt 文件,删除文件名的最后 6 个字符,将文件名中剩余的下划线替换为空格,但仍保留文件扩展名。

    所以假设这些是文本文件,您会看到如下内容:

    ABCDE_2015_10_20.txt
    HIJKL_2015_10_20.txt
    MNOPQ_2015_10_20.txt
    RSTUV_2015_10_20.txt
    

    变成这样:

    ABCDE 2015.txt
    HIJKL 2015.txt
    MNOPQ 2015.txt
    RSTUV 2015.txt
    

    【讨论】:

      【解决方案3】:

      如你想split文件名在第一个下划线,

      • .split() 方法或-split 运算符与从零开始的索引[0] 结合使用。
      • 重命名更改BaseName 并保留Extension

      Get-ChildItem 'E:\Thomson Reuters\Stage' |  
          Rename-Item -NewName { $_.BaseName.Split('_')[0] + $_.Extension }
      

      【讨论】:

        猜你喜欢
        • 2013-11-01
        • 2019-07-29
        • 1970-01-01
        • 1970-01-01
        • 2020-09-03
        • 1970-01-01
        • 2020-02-27
        • 2021-02-12
        • 2014-10-19
        相关资源
        最近更新 更多