简体   繁体   中英

Read each line of a txt file by looking for the first word at the beginning of each line and delete the line of file

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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