Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/457.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用JavaScript替换txt文件中的一行_Javascript_Node.js_Fs_Writefile_Appendfile - Fatal编程技术网

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

使用JavaScript替换txt文件中的一行,javascript,node.js,fs,writefile,appendfile,Javascript,Node.js,Fs,Writefile,Appendfile,我试图简单地用JavaScript替换文本文件中的一行 这个想法是: var oldLine = 'This is the old line'; var newLine = 'This new line replaces the old line'; 现在我想指定一个文件,找到oldLine并将其替换为newLine并保存它 有谁能帮我吗?这个就行了 var fs = require('fs') fs.readFile(someFile, 'utf8', function (err,data)

我试图简单地用JavaScript替换文本文件中的一行

这个想法是:

var oldLine = 'This is the old line';
var newLine = 'This new line replaces the old line';
现在我想指定一个文件,找到
oldLine
并将其替换为
newLine
并保存它

有谁能帮我吗?

这个就行了

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

以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”标志将“^”和$meta字符视为每行的开头和结尾,而不是整个字符串的开头或结尾

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

one line
a line to replace by something
third line
为此:

one line
a completely different line!
third line
可能重复的