【问题标题】:Replace a line in txt file using JavaScript使用 JavaScript 替换 txt 文件中的一行
【发布时间】:2022-01-19 08:07:47
【问题描述】:

我正在尝试使用 JavaScript 简单地替换文本文件中的一行。

想法是:

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

现在我要指定一个文件,找到oldLine 并将其替换为newLine 并保存。

谁能帮帮我?

【问题讨论】:

标签: javascript node.js fs writefile appendfile


【解决方案1】:

应该这样做

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);
 });
});

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      相关资源
      最近更新 更多