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!

Searching for records in a data file 1

Status
Not open for further replies.

perfectstorm

Programmer
Apr 23, 2001
2
CA
I'm trying to read a data file that has multiple records. Each record has a start and end word:
ie. hello(start) ---DATA--- goodbye(end)

how can I search for the start and end words and read the data
in between?

set input [open c:\hello.txt r]
set contents [split [read $input] \n ]
?
?

ty
 
Much as it pains me to admit it, I think this is a good case for regexp:
Code:
% set startwd "hello"
hello
% set endwd "goodbye"
goodbye
% set str $startwd
hello
% append str "abc def ghi 123 AAA"
helloabc def ghi 123 AAA
% append str $endwd
helloabc def ghi 123 AAAgoodbye

% regexp "($startwd)(.*)($endwd)" $str m m1 m2
1
% set m2
abc def ghi 123 AAA
%

_________________
Bob Rashkin
 
ty Bong but (forgive me) if you had multiple startwd and endwd in one file how would you iterate

ie.helloabc def ghi 123 AAAgoodbye; set var1
hellojkm nop qrs 456 BBBgoodbye; set var2
hellotuv wxy zzz 789 CCCgoodbye; set var3

etc..

thx again
 
You mean that startword and endword remain constant but occur in multiple strings with useful data in between, right? You could also do the case where the startword and endword, themselves change (with foreach but I don't think that's what you're saying.

Assuming the former, here's a general way:
1. read the file into a Tcl list (separated on linefeeds)
2. for each line in the file find all instances of your regexp

so:
Code:
set wd1 hello
set wd2 goodbye
set fid [open [red]<filename>[/red] r]
set linelist [split [read $fid] \n]
close $fid
foreach line $linelist {
   while {[regexp "($wd1)(.*)($wd2)" $line m m1 m2]>0} {
        [red]<do what you want with $m2>[/red]
        regsub "($wd1)(.*)($wd2)" $line "" line 
   }
}

_________________
Bob Rashkin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top