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

冷暖自知 提交于 2019-12-11 16:43:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!