# -*- tcl -*- # hello world # print a simple string on stdout puts "Hello World" # argv # access command line parameters (no segmentation fault accepted, nor silent exception, so some languages must explicitly check the presence of the argument) puts [lindex $argv 0] # env # access environment variable puts $env(HOME) # test file exists # return exit code error (non zero) if a file does not exist exit [expr ![file exists /etc/mtab]] # test file readable # return exit code error (non zero) if a file is not readable exit [expr ![file readable /etc/mtab]] # formatting # print integers in a simple formatted string set a 1; set b 2; puts "$a + $b = [expr $a + $b]" # system # call an external program and check the return value if {[catch {exec false}]} {puts stderr "false failed"} exec echo >@ stdout done # sed in place # remove #-comments from a file (modifying the file, i.e. in place) set f [lindex $argv 0] set fd [open $f r] regsub -all {#[^\n]*\n} [read $fd] {} contents close $fd set fd [open $f w] puts -nonewline $fd $contents close $fd # compile what must be # find and compile .c files into .o when the .o is old or absent proc doit {dir} { foreach f [glob -nocomplain $dir/*] { if [file isdir $f] { doit $f } elseif { [regsub \\.c$ $f .o o] && !( [file exists $o] && [file mtime $o] > [file mtime $f] ) } { puts "compiling $f to $o" exec gcc -c -o $o $f } } } doit . # grep # grep with -F -i -h handling, usage, grep'ing many files set i 0 set F 0 set ind 0 set usage 1 foreach s $argv { if { "$s" == "-i" } { set i 1 } elseif { "$s" == "-F" } { set F 1 } elseif { "$s" == "-h" } { incr usage } { incr usage -1 break } incr ind } if $usage { puts stderr {usage: grep [-F] [-i] regexp [files...]} exit 1 } set re [lindex $argv $ind] incr ind set files [lrange $argv $ind end] if $i { set re (?i)$re } if $F { set re (?q)$re } set nb [llength $files] proc grep { prefix fd re } { while {[gets $fd s] >= 0} { if [regexp $re $s] { puts $prefix$s } } } if { $nb == 0 } { grep "" stdin $re } { set prefix "" foreach f $files { if { $nb > 1 } { set prefix $f: } set fd [open $f] grep $prefix $fd $re close $fd } }