Tcl File Renamer

2007-Dec-03 This is a tool I wrote when I went to automatize file renaming. -- Sarnold

For example, you can prepend each file name by a prefix like this:

 tfrn head "The Beatles" *.mp3

this is useful for multimedia files which sometimes have cryptic names like "NoArtist - Track01.mp3", "IMG_5238.jpg", and so on... And it allows renaming with regexp patterns, which is so cool and funny... Better test it before to use it!


The script

 #! /usr/bin/env tclsh
 proc lfetch {lst} {
         upvar 1 $lst data
         return [nfetch data 1]
 }
 
 proc nfetch {lst n} {
         upvar 1 $lst data
         set x [lrange $data 0 [expr {$n-1}]]
         set data [lrange $data $n end]
         return $x
 }
 
 proc usage {} {
         puts {usage: tfrn command args... file1 ?file2 ... filen?
 "Tcl File ReNamer v1.0" renames massively files.
 trfn help:
         prints this message
 trfn head "header":
         prepend each file name with "header"
 trfn regexp "search" "replace":
         replaces matching "search" by "replace" using Tcl regsub command
 This is free software (c) Stephane Arnold 2007 (http://sarnold.free.fr/)}
         exit 0
 }
 
 interp alias {} Rename {} file rename
 proc debug {} {
         proc Rename {a b} {
                 puts [list rename $a $b]
                 file rename $a $b
         }
 }
 
 # subcommand
 set subcmd [lfetch argv]
 switch -glob -- $subcmd {
         head* {
                 set head [lfetch argv]
                 foreach f $argv {
                         Rename $f $head$f
                 }
         }
         reg* {
                 foreach {start replace} [nfetch argv 2] break
                 puts [list $start $replace]
                 foreach f $argv {
                         Rename $f [regsub -all -- $start $f $replace]
                 }
         }
         help - default {
                 usage
         }
 }