使用JavaScript替换txt文件中的一行

Wib*_*ers 2 javascript writefile fs node.js appendfile

我试图使用JavaScript替换文本文件中的一行。

这个想法是:

var oldLine = 'This is the old line';
var newLine = 'This new line replaces the old line';
Run Code Online (Sandbox Code Playgroud)

现在,我想指定一个文件,找到oldLine并用替换newLine并保存。

有人可以在这里帮助我吗?

小智 5

这应该做

var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {

  var formatted = data.replace(/This is the old line/g, 'This new line replaces the old line');

 fs.writeFile(someFile, formatted, 'utf8', function (err) {
    if (err) return console.log(err);
 });
});
Run Code Online (Sandbox Code Playgroud)


小智 5

如果要替换与字符串匹配的整行,而不仅仅是完全匹配的字符串,则仅以Shyam Tayal的答案为基础,而是执行以下操作:

fs.readFile(someFile', 'utf8', function(err, data) {
  let searchString = 'to replace';
  let re = new RegExp('^.*' + searchString + '.*$', 'gm');
  let formatted = data.replace(re, 'a completely different line!');

  fs.writeFile(someFile, formatted, 'utf8', function(err) {
    if (err) return console.log(err);
  });
});

Run Code Online (Sandbox Code Playgroud)

'm'标志会将^和$元字符视为每行的开头和结尾,而不是整个字符串的开头或结尾。

因此,以上代码将转换此txt文件:

one line
a line to replace by something
third line
Run Code Online (Sandbox Code Playgroud)

到这个:

one line
a completely different line!
third line
Run Code Online (Sandbox Code Playgroud)