Skip to content Skip to sidebar Skip to footer

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

Solution 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');

functionmain() {
  /// TODO: Replace filename with your filename.var filename = 'file.txt';

  /// TODO: Replace RegExp with your regular expression.var regex = newRegExp('Toto2.*\n', 'g');

  /// Read the file, and turn it into a stringvar 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 functionmain();

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!

Post a Comment for "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"