Search code examples
powershellfile-renamebatch-rename

How can I specify the position of the character I want to replace in a filename?


I am trying to rename several hundred TIFF files to follow a new naming convention. I've now hit a situation where I want to remove or change the 4th, 5th or 6th character in the file names.

The characters that I want to change are not necessarily unique in the file name.

For example:

APADA00010.tif

5th character = A
6th character = 0

Is there a way to specify that I want to change every 5th character to a hyphen, or to remove every 6th character?

I did find a similar query by another user but it was for insert instead of replace and so it didn't work:

get-childitem -Path .\ |
Rename-Item -NewName {$_.BaseName.insert(5,"-") + $_.Extension}

I'm very new to Powershell (just started fiddling with it last week) so I'd be very grateful if you included an explanation of how your solution works and what parts of your code mean.


Solution

  • You can do something like this to remove or replace specific sequenced characters:

    $string = "APADA00010.tif"
    $string.Remove("5", "1")
    
    $string = "APADA00010.tif"
    $string.Remove("4", "1").Insert(4, "-")
    

    Be aware that the index starts counting at 0 rather than 1.