Find and Replace in a txt file (xml file)

spierala's icon

Hi!

I?m new to max and javascript as well...

Is it possible with javascript to read a textfile and change there a certain string in a certain line?
I looked at the jsfiletester example. So I know how to read and write a file.
But how can I load the content of the txt file to a variable?

The best would be a find and replace object ;-)

cheers Flo

spierala's icon

ok so far I am:

function writefile(s)
{
    var f = new File(s,"write","TEXT");
    var s1 = 'test';
    var s2 = 'this';
    var s3 = 'text';

    if (f.isopen) {
        post("writing string to file: " + s2 + "n");
        f.writestring(s1);
        f.writestring(s2);
        f.writestring(s3);
        f.close();
    } else {
        post("could not create file: " + s + "n");
    }
}

i want to write an XML file. i have already the content of it. so i just have to paste it into the variables. but not so easy as expected...
if i paste the XML file to the variable JS has problems with the newlines and shift rights in the XML...
I attached the XML file which is basically a MOTION2 file. So you can try to paste it to one of the variables...
I also tried to get away with the newlines of the XML in the text editor but it won?t help.
I still get some error code like this:
? error: js: jsfiletester.js: Javascript SyntaxError: unterminated string literal, line 26
source line: lurSamples>1

cheers FLO

spierala's icon

sorry for the aweful selftalk topic ;-) but...
hey I?m very proud to present the find and replace script:

function rwlines(r,w,clip)
{
    var r = new File(r);
    var i,a,c;
    var w = new File(w,"write","TEXT");
    var s;
    var clip;
    var neu;

    if (r.isopen){
        post(clip);
        i=0;
        while (a=r.readline()) { // returns a string
            post("line[" + i + "]: " + a + "n");
            i++;
            if (a.search(/clip02.mov+/) != -1)
            {neu = a.replace(/clip02.mov/, clip);
w.writestring(neu + "n");}
else
{w.writestring(a + "n");}
        }
        r.close();
        w.close();
    } else {
        post("could not open file: " + s + "n");
    }
}

the only thing I don?t know yet, is how to save the new file in a certain folder...
cheers FLO

Joe X Med O''s icon

I guess in the file name the full path should be inserted...
you could do something like:
var w = new File("/your/full/path/to/the/folder/"+w,"write","TEXT");

You can make the user give the path to write, by using the object to get a folder path...


btw... Got here because I didn't know how to read and edit files in js...