how to display the input in a desired format
input file contains some contents such as :
15-05-2011 16:05 <DIR> .
15-05-2011 16:05 <DIR> ..
24-04-2011 16:07 <DIR> Administrator
15-05-2011 16:05 <DIR> confuser
01-02-2011 20:57 <DIR> Public
29-01-2011 19:28 <DIR> TechM
12-08-2011 09:36 <DIR> vt0013487
I need to give the file name in the command line argument
the output to be in the desired format:
Administrator 24-04-2011 16:07
confuser 15-05-2011 16:05
Public 01-02-2011 20:57
TechM 29-01-2011 19:28
vt0013487 12-08-2011 0开发者_Go百科9:36
So you're doing some fixed-width-field input parsing except that the final field is variable length and extends to the end of the line. That's easy enough. The only awkward bit is that we need to read in all the lines to get the width for the first field of the output format.
Assuming you supply the input on stdin (i.e., by redirection) and want it on stdout (so you can also redirect that to a file):
##### Read in and compute the width
set len 0
while {[gets stdin line] >= 0} {
set date [string range $line 0 16]
set name [string range $line 36 end]
lappend lines $name $date
if {[string length $name] > $len} {
set len [string length $name]
}
}
##### Write out as formatted
foreach {name date} $lines {
puts [format "%-*s %s" $len $name $date]
}
split
to break the input into lines, foreach
to iterate over them, regexp
to extract relevant groups of characters from those lines, format
to construct resulting strings (format
is often not needed in Tcl as simple variable substitution in strings usually works just okay for common cases).
Read this, this, this and this. Also this for the syntax used by the regexp
matching engine.
Also I suspect you may be trying to use the output generated by exec
'ing the DOS dir
command instead of using glob
to traverse directories and files natively. If so, this is wrong, use glob
This may not answer your question: If you are calling cmd /c dir
, here's a way to do it in Tcl:
package require struct::list
set files [glob *]
set maxlen [tcl::mathfunc::max {*}[struct::list map $files {apply {s {string length $s}}}]]
foreach file [lsort $files] {
set datetime [clock format [file mtime $file] -format {%d-%m-%Y %H:%M}]
puts [format {%-*s %s} $maxlen $file $datetime]
}
精彩评论