Tcl
renamefiles.tcl


return to misc index



This Tcl script provides a procedure for renaming files. The procedure accepts

  • the full path to a directory
  • the name of the files to be targeted
  • the new name
  • file extension

It is assumed the portion of the file name to be altered appears before the first period. For example, we may wish to rename all files beginning with untitled,

    untitled.0001.tif
    untitled.0002.tif
    etc...

to scene1

    scene1.0001.tif
    scene1.0002.tif
    etc...


Listing 1


proc renamefiles { dir oldname newname ext } {
    set files [glob -nocomplain -directory $dir *$ext]
    
    foreach item $files {
        # Ignore directories
        if { [file isdirectory $item] } continue
    
        # Get the filename
        set fname [file tail $item]
            
        # Tokenize the filename
        set parts [split $fname .]
            
        # Extract the first part of the name
        set name [lindex $parts 0]
            
        # We've found a match...
        if { [string equal $name $oldname] } {
            
            # Begin making a new file name
            set outname $newname 
            
            # Append the remaining "parts" of the filename
            set count [llength $parts]
            for { set i 1 } { $i < $count } { incr i } {
                append outname .[lindex $parts $i]
                }
            # Make the full path to the newly named file
            set dirname [file dirname $item] 
            set newpath [file join $dirname $outname]
            
            # Finally, rename the file
            file rename -force $item $newpath 
            }
        }
    }


The input parameters are:

renamefiles
    arguments
        dir        path to the source directory
        oldname    current name of the files to be renamed
        newname    new name for those files
        ext        only files with this extension will be renamed

    return value    
        none
Example:
    renamefiles  G:/tiffs  untitled  scene1  .tif



© 2002- Malcolm Kesson. All rights reserved.