在Txt文件中查找字符串,删除整行 [英] Find String in a Txt File, Delete Entire Line

查看:456
本文介绍了在Txt文件中查找字符串,删除整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用node.js创建一个IRC bot。机器人允许用户将歌曲链接添加到数据库。每当有人提交一首歌时,就会将其添加到新的shuffle.txt行中:

I'm currently working with node.js to create an IRC bot. The bot allows users to add song links to a database. Each time someone submits a song, it is added to a new line of "shuffle.txt" as such:

user1,The Beatles,Yesterday,(youtube link)
user2,The Rolling Stones,Angie,(youtube link)
user1,The Bealtes,Yellow Sumbarine,(youtube link)

请注意,user1在最新添加的内容中输错了一些信息。我正在尝试制作UNDO命令,以便用户可以删除最近输入的行。我打算通过在shuffle.txt中查找最新出现的名称并删除它所找到的整行来做到这一点。这是我的消息监听器:

Notice that user1 mistyped some information in their latest addition. I'm trying to make an UNDO command so that a user can delete their most recently entered line. I plan on doing this by finding the latest occurrence of their name in shuffle.txt and deleting the entire line that it's found on. Here's my message listener:

bot.addListener('message', function(from, to, message) {
    if (message.indexOf(config.prefix) == 0) {

        message = message.slice(1);
        var token = message.split(" ");

        if (token[0] == 'undo') {
              //find and delete
            }

    }
});

输入命令的用户从 >

the user entering the command is stored as from

我假设我必须按照以下方式做点什么:

I'm assuming I'll have to do something along the lines of this:

var songList = fs.readFileSync('shuffle.txt', 'utf8');
var position = songList.indexOf(from);

if (position != -1) { //if 'from' found

  //find LAST occurrence of 'from'
  //get length from here to next occurrence of '\n'
  //substr(length + 1)

  fs.writeFile('shuffle.txt', songList, function(err) {
    if (err) {
      console.log (err);
    }

}

我是JavaScript新手,这是我第一次使用node.js,所以我可以使用任何帮助!谢谢大家。

I'm new to JavaScript and this is my first time using node.js so I can use any help I can get! Thanks everyone.

编辑:我还应该指出,我不需要命令识别方面的帮助。我只需要查找/删除部分的帮助。干杯!

I should also point out that I don't need help with the command recognition. I only need help with the finding/deleting portion. Cheers!

推荐答案

Edit2:使用新解决方案进行编辑。

edited with a new solution.

您可以试试这个:

fs.readFile('shuffle.txt', function read(err, data) {
    if (err) {
        throw err;
    }

    lastIndex = function(){
        for (var i = data_array.length - 1; i > -1; i--)
        if (data_array[i].match('user1'))
            return i;
    }()

    delete data_array[lastIndex];

});

将文件拆分成行,找到带有简单循环的最后一行,使用<删除行code>删除,然后再将其修补。

Split file into lines, find the last line with a simple loop going backwards, remove the line using delete, then patch it back together.

演示

此外,你不应该使用 readFileSync in节点,因为它是单线程的,所以阻塞节点可能很危险。

Also, you should not use readFileSync in node, as blocking node can be dangerous since it's single threaded.

这篇关于在Txt文件中查找字符串,删除整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆