Mach1
Mach1

Reputation: 13

Remove nth character from filename in PowerShell

I have a large number of files in a number of directories with this type of naming convention:

"BU1_KCG_RANDOM_030515.csv", etc.

I need to remove the 16th and 17th characters. So the new file name would be "BU1_KCG_RANDOM_0515.csv".

How can I iterate the multiple directory renaming accordingly?

So far I have got the below, but I am not sure what would come next.

Get-ChildItem -Filter *.csv -Recurse | Rename-Item -NewName {$_.Name..................}

Upvotes: 0

Views: 1666

Answers (3)

fdomn-m
fdomn-m

Reputation: 28611

Bit basic, eg doesn't check if the file has already been renamed, but should get you to the next step

gci -filter *.csv -rec | % { Rename-Item $_ -newname ($_.Name.substring(0,15) + $_.Name.substring(17)) }

where

gci = get-childitem
% = for-each
$_ = this (inside the for-each)

Upvotes: 0

Matt
Matt

Reputation: 46680

I much prefer mjolinor's answer, but you can always do things in a different way with PowerShell. Since you can index a string like a char array we can use a little array notation to get the characters you want as well.

$oldname = "BU1_KCG_RANDOM_030515.csv"
$newname = -join $oldname[0..14 + 17..($oldname.Length)]
$newname
BU1_KCG_RANDOM_0515.csv

We also need to use -join to convert the array back into a string.

Upvotes: 0

mjolinor
mjolinor

Reputation: 68243

Using -replace:

Get-ChildItem -Filter *.csv -Recurse | 
foreach { $_ | rename-item -newname ($_.Name -replace '(.{15})..(.+)','$1$2')  }

Upvotes: 1

Related Questions