使用JavaScript替换txt文件中的一行
我试图简单地用JavaScript替换文本文件中的一行 这个想法是:使用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)
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
可能重复的