【问题标题】: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通过查找每行开头的第一个单词并删除文件的行来读取txt文件的每一行
【发布时间】:2019-02-21 10:32:56
【问题描述】:

想象一个这样的 txt 文件:

Toto1 线 Toto2 线 Toto3 线 ...

我想获取“Toto2”(或其他类似 Toto120)的整行,如果该行存在,则必须将其从 txt 文件中删除

txt 文件在以下之后将是这种形式:

Toto1 线 Toto3 线 ……

你有什么想法吗?

最好使用NodeJs的“fs”系统;它用于服务器端。

谢谢

【问题讨论】:

标签: javascript node.js fs


【解决方案1】:

使用fs 绝对是正确的方法,以及使用RegExp 查找要替换的字符串。这是我对您的回答的解决方案:

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

有关RegExp 的更多信息,有许多网站可以向您展示每个表达式的作用,例如:https://regex101.com/

希望这会有所帮助!

【讨论】:

  • 我不能给你一个“+1”,因为我收到了这个警告:声望低于 15 的人的投票被记录,但不要更改公开显示的帖子分数
猜你喜欢
  • 1970-01-01
  • 2012-06-08
  • 2013-10-09
  • 1970-01-01
  • 2022-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
相关资源
最近更新 更多