基于多列比较两个 csv 文件并保存在单独的文件中


Comparing two csv files based on multiple columns and save in separate file

我有两个格式相同的文件,其中一个有新的更新,另一个有旧的更新。没有特定的唯一 id 列。

如何仅提取新更新的行(使用 unix、PHP、AWK)?

你想"字节"将所有行与其他行进行比较,所以我会这样做:

$lines1 = file('file1.txt');
$lines2 = file('file2.txt');
$lookup = array();
foreach($lines1 as $line) {
  $key = crc32($line);
  if (!isset($lookup[$key])) $lookup[$key] = array();
  $lookup[$key][] = $line;
}
foreach($lines2 as $line) {
  $key = crc32($line);
  $found = false;
  if (isset($lookup[$key])) {
    foreach($lookup[$key] as $lookupLine) {
      if (strcmp($lookupLine, $line) == 0) {
        $found = true;
        break;
      }
    }
  }
  // check if not found
  if (!$found) {
    // output to file or do something
  }
}

请注意,如果文件非常大,这将消耗相当多的内存,您需要使用其他机制,但想法保持不变