问题描述
想象一个这样的txt文件:
Imagine a txt file like this:
Toto1 The line
Toto2 The line
Toto3 The line
...
我想获取"Toto2"(或其他类似Toto120)的整个行,如果该行存在,则必须将其从txt文件中删除
I would like to get the whole line of "Toto2" (or other like Toto120), and if the line exists then you have to remove it from the txt file
以下情况后,txt文件将采用以下格式:
The txt file will be of this form after:
Toto1 The line
Toto3 The line
....
你有个主意吗?
最好使用NodeJ的"fs"系统;它用于服务器端.
It is better to use the "fs" system of NodeJs; it is for the server side.
谢谢
推荐答案
使用fs
绝对是正确的方法,并且使用RegExp
查找要替换的字符串.这是我对您答案的解决方案:
Using fs
is definitely the right way to go, as well as using RegExp
to find the string you want to replace. Here is my solution to your answer:
var fs = require('fs');
function main() {
/// TODO: Replace filename with your filename.
var filename = 'file.txt';
/// TODO: Replace RegExp with your regular expression.
var regex = new RegExp('Toto2.*\n', 'g');
/// Read the file, and turn it into a string
var buffer = fs.readFileSync(filename);
var text = buffer.toString();
/// Replace all instances of the `regex`
text = text.replace(regex, '');
/// Write the file with the new `text`
fs.writeFileSync(filename, text);
}
/// Run the function
main();
此外,如果您需要更多使用fs
的资源,请查看以下链接: https://nodejs.org/api/fs.html
Furthermore, if you need more resources on using fs
check out this link: https://nodejs.org/api/fs.html
有关RegExp
的更多信息,有很多网站可以向您显示每种表达式的功能,例如: https ://regex101.com/
And for more information on RegExp
there are many websites that can show you what each expression does such as this one: https://regex101.com/
希望这会有所帮助!
这篇关于通过查找每行开头的第一个单词来读取txt文件的每一行,然后删除该行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!