PDA

View Full Version : How to replace character in a text file?


OZRay
05-29-2008, 05:26 PM
Hi scripters!

I was thinking that this is easy to do but after starting it I found that it's alot more complicated that I expected...
I have DXF file (text file) that I need to seek in and replace " by inches , by _
So I need to go read everything in the file line by line and replace those characters.
I know that I can do with with note pad or other text editor but it's something that
I need to do on new files everyday so I need to do it in msx to incorporate it into
other tools that I made.

Is there someone that can help me with this?
A kind of replace in file.


Regards,

OZRay

decapitator
05-29-2008, 08:00 PM
There might be a shorter solution but im just a beginner when it comes to maxscript but I did manage to get it to work.

I've created a function for you which worked here (need max2008+ since im using the substitudeString function from max, if you dont have those versions look up replace() in the max help, but that makes it a bit more complex since you need to find out the position of the characters in the file with findstring())

Anyhow here is my functionfn fReplace file str rep =
(
if (doesFileExist file) != false AND str.count == rep.count then --check if file exists and if replacements are equal
(
fs = openFile file mode:"r" --open the fileStream for reading only
content = readChars fs (getFileSize file) errorAtEOF:false --read filesize amount of chars (thats all) from file into variable.
close fs --close fileStream

for i = 1 to str.count do content = substituteString content str[i] rep[i] --set content to replace value

fs = openFile file mode:"w" --open file for writing and clear it
format content to:fs --write the content variable to the fileStream
close fs --close fileStream
)
)
fReplace "c:/tst.txt" #("\"",",") #("inches","_")
The usage is there as an example what it does is replace items from array 1 with array two so fReplace "path/to/file.whatever" #("Hello","world") #("Hi","there") in the string "Hello world!" would replace hello with hi, and world with there so in this case "Hi there!" is returned (to the file).

Hope this helps!

OZRay
05-29-2008, 08:36 PM
Wow! Thanks a lot !!!

This is what I was looking for!

Regards,

OZRay

CGTalk Moderation
05-29-2008, 08:36 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.