fsub: in-place substitution

if 0 {Richard Suchenwirth 2003-10-23 - I needed this tiny code to do regular expression substitution in files "in place" - the alternative would have been to fumble with Perl :(.

The code should be self-explanatory - maybe others can use this too. For use as a shell script, remove the space before #! in the first line and chmod +x. }

 #!/usr/bin/env tclsh
 proc fsub {re subst filename} {
    set fp [open $filename]
    set data [read $fp]
    close $fp

    set n [regsub -all $re $data $subst data]

    set fp [open $filename w]
    puts -nonewline $fp $data
    close $fp
    set n
 }

# This allows to execute this file as a shell script:

 if {[file tail [info script]] eq [file tail $argv0]} {
    if {$argv == ""} {
        puts "usage: fsub re subst file...
        substitute the regular expression 're' with 'subst'
        in all specified files"
    } else {
        foreach {re subst} $argv break
        foreach file [lrange $argv 2 end] {
            set n [fsub $re $subst $file]
            puts "$file : $n"
        }
    }
 }