简体   繁体   English

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

[英]Replace a line in txt file using JavaScript

I am trying to simply replace a line in a text file using JavaScript.我正在尝试使用 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.现在我想指定一个文件,找到oldLine并将其替换为newLine并保存。

Anyone who can help me here?谁能在这里帮助我?

Just building on Shyam Tayal's answer, if you want to replace an entire line matching your string, and not just an exact matching string do the following instead:只是建立在 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);
  });
});

The 'm' flag will treat the ^ and $ meta characters as the beginning and end of each line, not the beginning or end of the whole string. 'm' 标志会将 ^ 和 $ 元字符视为每行的开头和结尾,而不是整个字符串的开头或结尾。

So the above code would transform this txt file:所以上面的代码会转换这个txt文件:

one line
a line to replace by something
third line

into this:进入这个:

one line
a completely different line!
third line

This should do it这应该做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM