
tcl equivalent of NR in awk
Quote:
> Hi
> I'm new to this. And I have convert an awk script to tcl script. I have
> to read some arbitrary lines of a particular file and print it to another
> file. The reading has to be done by picking some specific lines here and
> there, and back and forth, and reading off some fields in the line into
> another file. awk does this by using the NR command. I wanted to
> find out if there is an equivalent of NR in tcl, instead of using many
> 'if' loops, which may take a long cpu time.
> Also if there's no such equivalent, what is the best way to do this.
> Please help
Since the awk NR is the record number, I assume that you're trying to
get specific lines from a file by their line number. The "Tcl way" to
do that, for small files that can be read entirely into memory, is to
read the data in one fell swoop, then split it into a list, like this:
set filename "myfile.dat"
set fp [open $filename "r"]
set data [split [read $fp [file size $filename]] "\n"]
close $fp
Then the variable 'data' contains a list of lines. You can get at a
specific line by using the list index function:
set p [lindex $data 122]
puts "line 122: '$p'"
If the original data file is very large, then you're stuck reading each
line in a loop. If you're planning on matching lines, then look at the
regular expression man pages. This is much more powerful than awk could
ever hope to be.
Bob
--
Mayo Foundation (507) 284-2702
Rochester MN, 55905 USA http://www.mayo.edu/sppdg/sppdg_home_page.html