Powershell - Rename filename by removing the last few characters

前端 未结 3 721
说谎
说谎 2021-01-19 01:02

I want to remove the last 11 characters of multiple files names. For example I have these file names:

ABCDE_2015_10_20
HIJKL_2015_10_20
MNOPQ_2015_10_20
RSTU         


        
相关标签:
3条回答
  • 2021-01-19 01:40

    Just to add to the response from arco444:

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

    This would rename all .txt files in the directory, remove the last 6 characters of the file name, replace any remaining underscore in the filename with a space but still retain the file extension.

    So assuming these were text files you would see something like this:

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

    Become this:

    ABCDE 2015.txt
    HIJKL 2015.txt
    MNOPQ 2015.txt
    RSTUV 2015.txt
    
    0 讨论(0)
  • 2021-01-19 01:40

    As you want to split the file name at the 1st underscore,

    • use the .split() method or -split operator with the zero based index [0].
    • rename changing the BaseName and keeping the Extension

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

    You're almost there, you just need to tell substring exactly where to start and end:

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

    By passing two integers to substring you give it the StartIndex and Length of the string you want to capture. See here for the documentation

    0 讨论(0)
提交回复
热议问题