Question

I have a text file that contains "unix style" line endings: a 0x0A at the end of each line.

I'm writing a script to modify that file, to add new content to it. This is JScript, running on Windows. The code looks like this:

    var fso = new ActiveXObject("Scripting.FileSystemObject"),
        fs = fso.openTextFile(src),
        origContent = fs.readAll();
    fs.Close();
    fso.MoveFile(src, dest);

    // write updated content to a new file.
    fs = fso.CreateTextFile(src);
    fs.WriteLine("# key: " + keyvaluee);
    fs.WriteLine("# group: " + groupvalue);
    fs.WriteLine(origContent);
    fs.Close();

The content of the resulting modified file is like this:

00000000: 2320 6b65 793a 2075 6e64 6566 696e 6564  # key: undefined
00000010: 0d0a 2320 6772 6f75 703a 2069 6d61 700d  ..# group: imap.
00000020: 0a23 636f 6e74 7269 6275 746f 7220 3a20  .#contributor : 
00000030: 416e 6472 6577 2047 776f 7a64 7a69 6577  Andrew Gwozdziew
00000040: 7963 7a20 3c77 6562 4061 7067 776f 7a2e  ycz <web@apgwoz.
00000050: 636f 6d3e 0a23 6e61 6d65 203a 2069 6d61  com>.#name : ima
00000060: 705f 6765 745f 7175 6f74 6172 6f6f 7428  p_get_quotaroot(
00000070: 2e2e 2e2c 202e 2e2e 290a 2320 2d2d 0a69  ..., ...).# --.i
00000080: 6d61 705f 6765 745f 7175 6f74 6172 6f6f  map_get_quotaroo
00000090: 7428 247b 696d 6170 5f73 7472 6561 6d7d  t(${imap_stream}
000000a0: 2c20 247b 7175 6f74 615f 726f 6f74 7d29  , ${quota_root})
000000b0: 2430 0d0a                                $0..

As you can see, the lines added with the JScript TextStream end in 0D 0A, while the existing content ends each line in simply 0A. See the sequence at position 0x10 and compare to the byte at position 0x54. This is a text file, I'm just showing the content in hex.

How can I make the line endings consistent in the modified file? Either way is fine with me, I just don't like using both in the same file.

Can I convert the origContent string in memory to use "DOS style" line endings?

Was it helpful?

Solution

I just used a string replace with hex encoding. This worked for me.

var fso = new ActiveXObject("Scripting.FileSystemObject"),  
    fs = fso.openTextFile(src),  
    origContent = fs.readAll(),  
    re1 = new RegExp("\x0A", 'g');

fs.Close();  
fso.MoveFile(src, dest);  

// write updated content to a new file.  
fs = fso.CreateTextFile(src);  
fs.WriteLine("# key: " + keyvaluee);  
fs.WriteLine("# group: " + groupvalue); 
origContent = origContent.replace(re1, "\x0D\x0A");
fs.WriteLine(origContent);  
fs.Close();  

The result is that all the line-endings in origContent get converted to CR/LF rather than just LF. This works only if there are no CRLF pairs in the original file - only if it had all unix line endings, originally.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top