Active Forums => QB64 Discussion => Topic started by: IronMan on October 14, 2020, 09:21:09 pm
Title: Need small piece of code that will search and replace a word in a text file.
Post by: IronMan on October 14, 2020, 09:21:09 pm
I'm needing a small piece of code that will search and replace a word in a text file. Must search the entire file, and replace all entries found. I did have this saved but lost it and can't remember how to do it. Any help appreciated. Thank you.
Title: Re: Need small piece of code that will search and replace a word in a text file.
Post by: bplus on October 14, 2020, 09:46:50 pm
INSTR will search a string of any length and you can restart where you left off in search.
To replace, checkout MID$ the statement not the function, something like:
p = instr(Filestuff$, searchMe$) while p mid$(Filestuff$, p, len(seachMe$) = replacement$ p = instr(p+1, Filestuff$, searchMe$) wend
test a bit.
Title: Re: Need small piece of code that will search and replace a word in a text file.
Post by: SMcNeill on October 14, 2020, 10:08:12 pm
Just be careful of false positives.
For example, you want to change DOG to CAT in the following:
The dog has been biting the dog’s ass, for eating all the dogfood.
In this case, you only want to change “dog” and not “dog’s” or “dogfood”, so you end up with:
The cat has been biting the dog’s ass, for eating all the dogfood.
The trick here, is to actually change “ dog “ to “ cat “ (see the space before and after?), to rule out any false positives in your string changing.
Just something to be careful of, and something many worthless profanity filters fail to do...
“ass” is profanity, so it becomes a “***”.
Ergo, we see stuff such as “***istance wanted by a high class ******in for Great ***et Quest”
Title: Re: Need small piece of code that will search and replace a word in a text file.
Post by: IronMan on October 15, 2020, 06:18:57 pm
OK guys I got it and wanted to post in the event anyone else ever needs it.
This works perfect!
CALL Replace
PRINT "Complete"
SUB Replace () text$ = ""
OPEN "FRUIT.txt" FOR INPUT AS #1 DO WHILE NOT EOF(1) LINE INPUT #1, line$ text$ = text$ + line$ + CHR$(13) + CHR$(10) LOOP CLOSE #1