Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to get the index of the nth line of a file?

Status
Not open for further replies.

RajVerma

Programmer
Jun 11, 2003
62
DE


thanq ulis.
can anyone give me a simple syntax for getting the index of the number of line in the file. suppose I want to fetch the first string of the 3rd line in the file!! I used the following code.

# This is to fetch the data from the file into the window
set path  [format "/xwinnmr/tcl/xwish_scripts/iu_acqu.txt"]
set file [open $path r]
foreach line [split [read $file] \n] {
set index [string range [lindex $line 0] 0 end]
set freq1 [string range [lindex $line 1] 0 end]
set time1 [string range [lindex $line 2] 0 end]
}
close $file

this way it's fetching the strings only from the last line. so wat to do if I want to get acess to the ith line?

thanks in advance.
 
I don't understand why you're mixing strings and lists.
First you split the file on newlines and make a list of lines. So far so good. Each line is now a string (of length = [string length $line]). So, you say you want the 3rd line:
set linelist [split [read $file] \n]
set line [lindex $linelist 2];#indexing starts at 0

Now, what do you mean by the first string?

Bob Rashkin
rrashkin@csc.com
 
you're close. The problem with your foreach loop is that it sets those three variables for each and every line, and the only data being kept in the end is that last line. Here what i'd do if i were you.
Get rid of the loop, if you know you are looking for the ith line then theres no need for it.


set buff [read $file]
set split_buff [split $buff \n]

#you will need to adjust the ranges on the below lines to reflect the actual rages of the string

set index [string range [lindex $split_buff $i] 0 1]
set freq1 [string range [lindex $split_buff $i] 2 3]
set time1 [string range [lindex $split_buff $i] 4 5]

 
I still prefer to use an array and gets for this though
the other method with a list is simpler.

Code:
proc loadfile {fname} {
global fileloaded
set x 0
   if {![catch {set fd [open $fname r]}]} {
        while {[gets $fd line] > -1} { 
              set fileloaded([incr x]) $line
        } 
        close $fd    
        return $x
   }
return -1
}
 if {[set tt [loadfile /home/scrap.txt]] > 0} {
       puts "[array get fileloaded $tt]"
  }
3 {John saw Jane}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top