tclfilereadertk-toolkitfile-readtcltk

To find line index and word index by reading a text file


I have just started learning Tcl, can someone help me how to find line index and word index for a particular word by reading a text file using Tcl.

Thank you


Solution

  • As mentioned in the comments, there is a lot of basic commands you might utilize to solve your problem. To read a file into a list of lines you could use open, split, read and close commands as follows:

    set file_name "x.txt"
    # Open a file in a read mode
    set handle [open $file_name r]
    # Create a list of lines
    set lines [split [read $handle] "\n"]
    close $handle
    

    Finding a certain word in a list of lines might be achieved by using a for loop, incr and a set of lists related commands like llength, lindex and lsearch. Every string in Tcl can be interpreted and processed as a list. The implementation might look like this:

    # Searching for a word "word"
    set neddle "word"
    set w -1
    # For each line (you can use `foreach` command here)
    for {set l 0} {$l < [llength $lines]} {incr l} {
      # Treat a line as a list and search for a word
      if {[set w [lsearch [lindex $lines $l] $neddle]] != -1} {
        # Exit the loop if you found the word
        break
      }
    }
    
    if {$w != -1} {
      puts "Word '$neddle' found. Line index is $l. Word index is $w."
    } else {
      puts "Word '$neddle' not found."
    }
    

    Here, the script iterates over the lines and searches each one for a given word as if it was a list. Executing a list command on a string splits it by space by default. The loop stops when a word is found in a line (when lsearch returns a non-negative index).

    Also note, that the list commands are treating multiple spaces as a single separator. In this case it seems to be a desired behavior. Using split command on a string with a double space would effectively create a "zero length word" which might yield an incorrect word index.