Reputation: 31
I have a big amount of files in a folder named "01-aaa-bbb-ccc", "02-ddd-eee-fff" and so on. In another folder I have an early version of the same files without the index (that was added manually in order to sort them in a specific order) "aaa-bbb-ccc", "ddd-eee-fff". I'd like to use the early version but I need to rename them adding the same index as in the other folder.
Basically, something like: rename the files in folder b in the same way as the onse in folder a if the filename without the index is the same.
Is there a way to do it in powershell? Unfortunately my skills are not good enough for that. Thank you for your help!
Upvotes: 3
Views: 853
Reputation: 12493
Get-ChildItem .\a\* | Select -Expand Name | %{ $_ -match "([\d]+)-(.+)" } | `
%{ Rename-Item -WhatIf .\b\$($matches[2]) $matches[0] }
Upvotes: 0
Reputation: 202092
Here's a similar approach. Works in my small bit of testing:
$newNames = Get-ChildItem ..\a -Name
# Cd into b dir
Get-ChildItem | Foreach {$name = $newNames -match "\d+-$_";if ($name){$_}} |
Rename-Item -NewName {$name}
Upvotes: 2
Reputation: 354864
$ht = @{}
Get-ChildItem a\* | Select-Object -ExpandProperty name | ForEach-Object {
$null = $_ -match '(\d+)-(.*)'
$ht[$Matches[2]] = $Matches[1]
}
Get-ChildItem b\* | ForEach-Object { Rename-Item $_ ($ht[$_.name] + '-' + $_.name) }
First I create a hash table which contains a mapping of the file name without the index to the index to use. This is then used to rename the items in folder b accordingly.
Upvotes: 1