11

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
RSTUV_2015_10_20

would like to rename them to

ABCDE
HIJKL
MNOPQ
RSTUV

I have tried using the follwing code:

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

Can anybody tell me where I am going wrong?

arco444
  • 22,002
  • 12
  • 63
  • 67
Sayful Ahmed
  • 225
  • 2
  • 3
  • 8
  • And have you made any attempt to solve this yourself? – arco444 Oct 21 '15 at 09:42
  • Yes - i can remove the characters from the start of the filename but not the last using the following: Get-ChildItem 'E:\Thomson Reuters\Stage' | rename-item -newname { [string]($_.name).substring($_.name.length -14) } – Sayful Ahmed Oct 21 '15 at 09:43
  • Please [edit](http://stackoverflow.com/posts/33255834/edit) the question and update it with the code you wrote so far then – arco444 Oct 21 '15 at 09:45

3 Answers3

14

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

arco444
  • 22,002
  • 12
  • 63
  • 67
11

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
Community
  • 1
  • 1
Mike
  • 111
  • 1
  • 2
5

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 }