如何在csv或txt中找到缺失的行? (复杂)

问题描述 投票:-3回答:2

这是一个例子......

档案1:

1; 01812345; BB100

2; 018ACBA5; BB100

3; 01955555; BB100

10; 01901022; BB100

文件2 :(不同的mac地址,缺少3;)

1; 01866666; BB101

2; 01877777; BB101

10; 01988888; BB101

如何快速确定我缺少3;?我无法比较整行,因为我只需要在第一个;之前比较第一个整数值

我需要一些自动化解决方案,因为我使用300个地址的列表,而不是连续的。

csv line difference
2个回答
1
投票

在对我的另一个答案的评论中,你说,这项任务是你经常做的事情,你也表达了自动化的愿望。这是一个小型的C ++程序,应该可以工作:像prg file1 file2一样使用它来查找file1中的行,其中包含file2中缺少的键。要从file1中删除行,请切换参数的顺序:prg file2 file1

#include <iostream>
#include <string>
#include <map>
#include <fstream>

using namespace std;

typedef map< string, string > tMap;

bool readFileIntoMap( string fn, tMap &m) 
{
    ifstream inFile( fn, std::ios::in);
    if( !inFile.good() ){
        std::cout << "Could not open " << fn << std::endl;
        return false;
    }

    string key, aLine;
    string::size_type pos;
    while ( inFile ) {
        getline( inFile, aLine ) ;

        pos = aLine.find( ';' );
        if( pos != string::npos ) {
            key = aLine.substr(0, pos);
        } else {
            key = "-1";
        }

        m[ key ] = aLine; // map key to complete line
    } // of while
    return true;
}

// check for each key of first file: if the key is present in the
// second file, if not: report the line from the first file 
void findMissingKeys( tMap &leftMap,  tMap &rightMap)
{
    string leftKey;
    for( auto &leftElem : leftMap) {
        leftKey = leftElem.first;

        auto it =  rightMap.find( leftKey );
        if( it == rightMap.end() ) {
            // report missing line in second file
            cout << leftElem.second << endl;
        }
    }
}

int main( int argc, char* argv[] ) {
    if ( argc != 3 ) {
        cerr << "Please provide exactly two filenames as argument!" << endl;
        cerr << "Program will dump lines with a key present in first and missing in second file." << endl;
        return 1;
    }

    tMap m1, m2;

    readFileIntoMap( argv[1], m1 );
    readFileIntoMap( argv[2], m2 );

    findMissingKeys(m1,m2);
}

1
投票
  1. 创建每个文件的副本。
  2. 使用正则表达式替换分号后删除部分: 找到什么:qazxsw poi 替换为:(留空) 检查左下角的**正则表达式* 单击全部替换
  3. 对每个副本进行排序(编辑 - >线路操作 - >排序)。 也许在排序之后,您可以通过查看文件找到其他行,否则继续执行后续步骤。
  4. 比较排序版本:差异为您提供一个或另一个文件中的行(您的原始未排序文件)。有几种选项可以自动进行比较: 有一个名为Compare的记事本++插件,您可以通过插件管理器安装它 你可以使用像winmerge这样的单独程序
  5. 一旦知道了该行,就可以查找缺失的行并将其添加到另一个文件中

另一种选择是将两个文件的行插入新文件中,然后对新文件进行排序。现在,您需要在第一列中找到具有唯一编号的行。但我会使用比较工具或比较插件,如上所述。这使得差异更容易发现。

© www.soinside.com 2019 - 2024. All rights reserved.