Skip to content Skip to sidebar Skip to footer

Javascript: Replace Last Line In .txt File

I wish to open a file and replace the last line. Not the empty last line, the last last with text, forexample; Line1 Line2 Line3 I would like to transform this into Line1 Line2 La

Solution 1:

With Windows Scripting Host:

var fso = new ActiveXObject("Scripting.FileSystemObject");

var fh = fso.OpenTextFile("test.txt");
var lines = fh.ReadAll();
fh.Close();

lines = lines.split('\r\n');
lines = lines.slice(0, -2);
lines.push('Last Line');
lines = lines.join('\r\n');

var fh = fso.CreateTextFile("test.txt", true);
fh.Write(lines);
fh.Close();

Post a Comment for "Javascript: Replace Last Line In .txt File"