查找字符串并删除行-Node.JS [英] Find string and delete line - Node.JS

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

问题描述

如何在node.js中读取文件,搜索字符串并删除行?我尝试过

How to read file, search for string and delete line in node.js? I have tried

var fs = require('fs')
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];

});

推荐答案

假设我们有一个文本文件 shuffle.txt 包含以下内容

Let's say we have a text file, shuffle.txt contains the following content

john
doe
user1 
some keyword
last word

现在,我们阅读 shuffle.txt 文件,然后搜索" user1 "关键字.如果任何行包含" user1 ",那么我们将删除该行.

Now we read the shuffle.txt file and then search for 'user1' keyword. If any line contains the 'user1', then we will remove the line.

var fs = require('fs')
fs.readFile('shuffle.txt', {encoding: 'utf-8'}, function(err, data) {
    if (err) throw error;

    let dataArray = data.split('\n'); // convert file data in an array
    const searchKeyword = 'user1'; // we are looking for a line, contains, key word 'user1' in the file
    let lastIndex = -1; // let say, we have not found the keyword

    for (let index=0; index<dataArray.length; index++) {
        if (dataArray[index].includes(searchKeyword)) { // check if a line contains the 'user1' keyword
            lastIndex = index; // found a line includes a 'user1' keyword
            break; 
        }
    }

    dataArray.splice(lastIndex, 1); // remove the keyword 'user1' from the data Array

    // UPDATE FILE WITH NEW DATA
    // IN CASE YOU WANT TO UPDATE THE CONTENT IN YOUR FILE
    // THIS WILL REMOVE THE LINE CONTAINS 'user1' IN YOUR shuffle.txt FILE
    const updatedData = dataArray.join('\n');
    fs.writeFile('shuffle.txt', updatedData, (err) => {
        if (err) throw err;
        console.log ('Successfully updated the file data');
    });

});

在这里,如果一行包含" user1 "关键字,我们将删除整行.新的 shuffle.txt 文件将不再包含带有'user1'关键字的行.更新后的 shuffle.txt 文件看起来像

Here, if a line contains 'user1' keyword, we are removing the entire line. The new shuffle.txt file will be no longer contains a line with 'user1' keyword. The updated shuffle.txt file looks like

john
doe
some keyword
last word

有关更多信息,请参见 doc .

For more information check the doc.

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

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