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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to search for a string!

Status
Not open for further replies.

JohnMorrison

Technical User
Feb 22, 2001
1
GB
I think this should be straightforward, but I am new to tcl so I need some help.

Basically, I need to search for a string within a file, and if the string is found, then write a message to indicate that it has been found (something like the 'grep' command in Unix).

i.e. Something like : search &quot;<String>&quot; filename
if string found <write OK message>
else <Write error message>
Thanks in advance

John
 
proc grep {pattern filename} {
set fp [open $filename]
for {set found 0} {![eof $fp] && !$found} {} {
set found [regexp $pattern [gets $fp]]
}
close $fp

return $found
}

Example usage:

if {[grep {abc} file1.txt]} {
puts &quot;OK&quot;
} else {
puts &quot;not found&quot;
}

Note that link grep in UNIX, the pattern may
contain regular expressions.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top