5

I am trying to simply replace a line in a text file using JavaScript.

The idea is:

var oldLine = 'This is the old line';
var newLine = 'This new line replaces the old line';

Now i want to specify a file, find the oldLine and replace it with the newLine and save it.

Anyone who can help me here?

4

2 回答 2

13

只是建立在 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);
  });
});

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

所以上面的代码会转换这个txt文件:

one line
a line to replace by something
third line

进入这个:

one line
a completely different line!
third line
于 2019-05-14T15:38:03.777 回答
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);
 });
});
于 2018-11-23T12:19:11.307 回答