return to misc index

This Tcl script provides a procedure for adding padding to a file name. For example, given a name such as,


it would return this name


The procedure assumes the numeric extension to be padded to 4 digits follows the actual name of the file and is separated by periods. For this reason the "extra" numeric extension of ".1." has not been effected. This procedure will not work with an input name that does not separate the numeric extension with a leading period, for example,


would be incorrectly returned as,


Listing 1

proc padding { oldname } {
    # Tokenize the filename
    set parts [split $oldname .]
    # Extract the numeric extension
    set numeric [lindex $parts 1]
    # Make sure an extra zero is added only to
    # filenames with a padding of 3 digits
    if { [string length $numeric] < 4 } {
        set numeric 0$numeric
    # Begin making a new file name
    set filename [lindex $parts 0].$numeric
    # Append the remaining "parts" of the filename
    set count [llength $parts]
    for { set i 2 } { $i < $count } { incr i 1 } {
        append filename .[lindex $parts $i]
    return $filename

The input parameters are:

    name    the name of a file

Return value    
      the new file name
    set oldname "untitled.021.0001.tif"
    set newname [padding $oldname]
    puts $newname

© 2002- Malcolm Kesson. All rights reserved.