Looking for a search string in a file and printing next word in that line
19,444
Solution 1
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.
Solution 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.
Author by
Yashwanth Nataraj
Updated on June 14, 2022Comments
-
Yashwanth Nataraj almost 2 years
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??