Replacing numbered file names with different number without conflicting with other files in folder

Viewed 28

I have hundreds of images that were automatically saved on different occasions using different a scheme, and I'm trying to make them consistent. I feel like this should be really simple in Powershell, but I'm not familiar with it.

Currently, I have a bunch of .txt and .tif files named U6Co_AsFab_(####)_raw for indexes from 0118 to 0141 as follows:

U6Co_AsFab_(0118)_raw.tif  
U6Co_AsFab_(0118)_raw.txt  
U6Co_AsFab_(0119)_raw.tif  
U6Co_AsFab_(0119)_raw.txt  
            *  
            *  
            *  
U6Co_AsFab_(0141 )_raw.tif  
U6Co_AsFab_(0141 )_raw.txt 

and I need them to be shifted to range from 0139 to 0162 as follows:

U6Co_AsFab_(0139)_raw.tif  
U6Co_AsFab_(0139)_raw.txt  
U6Co_AsFab_(0140)_raw.tif  
U6Co_AsFab_(0140)_raw.txt  
             *  
             *  
             *  
U6Co_AsFab_(0162)_raw.tif  
U6Co_AsFab_(0162)_raw.txt  

In the mix are U6Co_AsFab_(####) (without raw) that are indexed correctly.

I ran the following in Powershell:

Get-ChildItem U6Co_AsFab_* -Include *raw* | 
    Where { $_ -match 'U6Co_AsFab_(\d+)' } | 
        Foreach { $num = [int]$matches[1] + 21; Rename-Item $_ (("U6Co_AsFab_{0:0000}" + $_.Extension) -f $num) }

And the filenames conflicted with ones that had yet to be renamed, giving this error:

Rename-Item : Cannot create a file when that file already exists.

I was thinking I could add an If-Else argument that would only rename the file if it didn't already exist in the directory. Then it seems like I could re-execute that code until all the files were re-numbered.

What is the best way to do this? I have a similar issue in other folders as well.

1 Answers

The problem is basically, that you increase each index one by one, but the files with the higher indexes already exist. You need to reverse the order.

Try this:

$files = @(Get-ChildItem U6Co_AsFab_* -Include *raw*)
[Array]::Reverse($files)
# your remaining code should work fine
$files | where { $_ -match 'U6Co_AsFab_(\d+)' } | 
  foreach {
     $num = [int]$matches[1] + 21
     Rename-Item $_ (("U6Co_AsFab_{0:0000}" + $_.Extension) -f $num)
  }
Related