#! /bin/sh # next line is a comment to tcl, but not sh: \ P=/opt/bin:$PATH ; for i in /opt/tcl* ; do P=$i/bin:$P ; done ; \ PATH=$P ; export PATH ; exec tclsh $0 ${1+"$@"} set prog [file tail $argv0] set Prog [string toupper [string index $prog 0]][string range $prog 1 end] proc usage {} { puts "Usage: $::prog \[-left|-right] \[-what trimchars] \[file...] $::Prog deletes leading and/or trailing whitespace from each line of of each file named on the command line (default stdin). The result is printed to stdout. Options: -------- -left only trim the left side (ie, leading whitespace). -right only trim the right side (ie, trailing whitespace). -what sss Trim the characters listed in in sss, instead of whitespace. -nnn Truncate line to nnn characters, after trimming is done. -nnnw Truncate line to nnn screen widths, after trimming is done." } proc mustbe {o opt} { if ![string match "$o*" $opt] { puts "$::Prog: unknown option $o." exit 1 } } set nmax "end" set op trim while {[llength $argv] && [string match -* [set o [lindex $argv 0]]]} { switch -regexp -- $o { {^-l} {mustbe $o -left; set op trimleft ; set argv [lrange $argv 1 end] } {^-r} {mustbe $o -right; set op trimright ; set argv [lrange $argv 1 end] } {^-w} {mustbe $o -what; set trimchars [lindex $argv 1]; set argv [lrange $argv 2 end] } {^-[0-9]+$} { set nmax [expr -$o]; set argv [lrange $argv 1 end]} {^-[0-9]+[wW]$} { foreach {rows cols} [exec screensize] {break} set nmax [string range $o 1 [expr [string length $o] - 2]] set nmax [expr $nmax * $cols] set argv [lrange $argv 1 end] } -- { set argv [lrange $argv 1 end]; break } -* { usage ; exit 0 } } } if ![llength $argv] { set argv "-" } proc trunc {n s} { string range $s 0 $n } if [string compare $nmax "end"] { incr nmax -1 ; # because "string range" used 0-based indexing } foreach fname $argv { if {[string compare $fname "-"] == 0} { set handle stdin } elseif [catch {open $fname r} handle] { puts stderr $handle continue } if [info exists trimchars] { foreach line [split [read -nonewline $handle] \n] { puts [trunc $nmax [string $op $line $trimchars]] } } else { foreach line [split [read -nonewline $handle] \n] { puts [trunc $nmax [string $op $line]] } } if [string compare $handle stdin] { close $handle } }