search and replace text in text file from access

F

fly_by_night

Is there a way to search and replace a piece of text in a text file from an
Access module?

Any help is appreciated. thanks!
 
A

Allen Browne

The safe way to do this with pure VBA would be:
- Open the file for input
- Open a temp file for output
- InputLine
- Replace()
- Print #
- Loop until EOF
- Close both
- Kill the orginal
- Name the 2nd as the first.
 
B

Bas Cost Budde

Peter said:
But God help you if the Search and/or Replacement strings may include
1 or more CRLFs!!

All except for that God doesn't write VBA. At least I never see Him post
on these fora...

Seriously, the InputLine part would need revision in that case.
 
D

Dirk Goldgar

Bas Cost Budde said:
All except for that God doesn't write VBA. At least I never see Him
post on these fora...

Seriously, the InputLine part would need revision in that case.

At worst, read the whole text file into a String variable in one gulp
(if it's not too big), and then just replace within that variable and
write it out again.
 
D

Dirk Goldgar

Peter R. Fletcher said:
The "if it's not too big" is potentially a very big "if".

You betcha.
The textbook way to do this, assuming that you do need to handle
included CRLFs and/or other control characters, _and_ that you need to
handle files of arbitrary (i.e. large!) size, would probably be to
open the file as binary, read it in fixed-length chunks, and
"double-buffer" the input in such a way that matches would be
guaranteed to be found even if they fall across block margins. The
details of the most efficient way of doing this would depend on your
scanning algorithm.

Fortunately, text files don't tend to be arbitrarily large.
 
J

John Nurick

The "if it's not too big" is potentially a very big "if".

IIRC the maximum length of a VBA string is 2GB, so the real constraint
is set by the available virtual memory and the way that a Replace()
would involve keeping more than one copy of the string in memory at a
time. So with an average modern machine it should be possible to handle
files of several, if not many, megabytes this way without problems. (I
routinely write Perl code that does this, but haven't yet needed to try
it in any dialect of VB).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top