问题
Imagine a txt file like this:
Toto1 The line Toto2 The line Toto3 The line ...
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
The txt file will be of this form after:
Toto1 The line Toto3 The line ....
Do you have an idea?
It is better to use the "fs" system of NodeJs; it is for the server side.
Thank
回答1:
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();
Furthermore, if you need more resources on using fs
check out this link: https://nodejs.org/api/fs.html
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/
Hope this helps!
来源:https://stackoverflow.com/questions/52368778/read-each-line-of-a-txt-file-by-looking-for-the-first-word-at-the-beginning-of-e