2

for example, consider a file "abc.txt" has following content

{apple_Text "1"}

{banana_Text "2"}

{orange_Text "3"}

Now, I want to search "apple_Text" keyword in that file and if found it should print second column value in that, i.e. "1". Can I know how to do that in Tcl??

serenesat
  • 4,611
  • 10
  • 37
  • 53
Yashwanth Nataraj
  • 183
  • 3
  • 5
  • 16

3 Answers3

5

Here is my solution:

set f [open abc.txt]
while {[gets $f line] != -1} {
    if {[regexp {apple_Text\s+"(.*)"} $line all value]} {
        puts $value
    }
}
close $f

Basically, I search each line for "apple_Text" and extract the value from the line.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93
2

Here a sweet short solution:

set fd [open abc.txt r]
set data [read $fd]
close $fd
puts [lindex [lsearch -inline -index 0 -inline $data "apple_Text"] 1]

This will only find the first result through.

I consider the input as a valid Tcl list of Tcl lists. ({apple_Text "1"} is a Tcl list with 1 element: apple_Text "1", which is itself a valid Tcl list with 2 elements: apple_Text and 1)
If this does not match your input, then things are a little bit more complicated.

Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
0

You could use the following

set fp [open "abc.txt" r]
set filecontent [read $fp]
set input_list [split $filecontent "\n"]
set appleTextList [lsearch -all -inline $input_list "apple_Text*"]
foreach elem $appleTextList {
    puts "[lindex $elem 1]"
}
close $fp
Varun
  • 691
  • 4
  • 9