【问题标题】:compare two .csv files using awk\ unix使用 awk\ unix 比较两个 .csv 文件
【发布时间】:2014-10-12 02:15:11
【问题描述】:

文件1:

SA, 5006, 12, , DJ
CN, BN, , BBB, 13
22, 67, GG, FF, 88
33, BB, AA, CC, 22

文件2:

SA, 5006, 12, 15 , DJ
CN, BN, , BBB, 13
empty line
33, CC, AA, dd, 22

输出:

SA, 5006, 12, 15 , DJ, unmatch, 4
CN, BN, , BBB, 13, match
empt, empt, empt, empt, empt, unmatch, 12345
33, CC, AA, dd, 22, unmatch, 24

我需要逐行比较两个 .csv 文件,但某些字段/行可以为空,并且输出应该在 file3 中: 5列形成文件2,匹配\不匹配,不匹配这样的字段:

c1, c2, c3, c4, c5, match/unmatch, concatenation of digits representing unmatch fields.

我尝试了一些东西,但是我是 awk 的新手,有人可以帮忙吗? :)

我使用的代码,但我认为问题出在空字段和我不知道如何打印:

 ##Set input and output field separators to ':'.
BEGIN {
    FS = OFS = ":"
}


NR == FNR {
    ## save all the line in an array, so lines will be saved like:
    ## c1::c2::c3::c4::c5

    ++a[$0]

    ## Process next line from the beginning.
    next
}

## for every line of second file.
{ 

    ## Search for the line in the array, if not exists it means that any field is     different  
    ## print the line.
    if ( !a[$0] ) {
            $6 = "same"
            print
    }else {
   $6 = " not same"
            print
}
}

【问题讨论】:

  • 最后一行的输出是否应该只是... unmatch, 2 而不是24
  • 文件使用,时,为什么要将字段分隔符设置为:
  • 嗨@jaypal IT 应该是 24 岁了(:
  • @YifatKatrielUdi 即使这样,输出仍然是错误的。输出中应该是dd,而不是CC?输出是否应该包含来自 file1 或 file2 的行?
  • @jaypal,是的!我的错误(:你说得对

标签: shell unix csv awk


【解决方案1】:

你需要使用行号作为你在文件之间保存的数组的索引,这样你就可以比较两个文件中对应的行。

BEGIN { FS = ", "; }
NR == FNR { a[FNR] = $0 } # In first file, just save each line in an array
NR != FNR { if (a[FNR] == $0) { # Compare line in 2nd file to corresponding line in first file
                $6 = "match";
            } else {
                $6 = "unmatch";
                split(a[FNR], b); # Split up the fields from the first file
                $7 = ""
                for (i = 1; i <= 5; i++) { # Compare each field
                    if ($i != b[i]) { $7 = $7 i; } # Add non-matching field numbers to output
                }
            }
            print;
        }

【讨论】:

  • 太快了!谢谢@barmar,如果你能做笔记,我会很高兴,所以我可以从中学习,如果不难的话:)
  • 我添加了 cmets,它们有用吗?
  • 好的(:我,看到了,我不明白,昨天看到2个答案,今天只有一个,为什么?
  • 首先匹配/不匹配出现在字段 5 中,而不是在单独字段中,其次如果我有两个并行空行,它看起来不匹配/:
  • 另一个答案的作者昨天删除了。
猜你喜欢
  • 2012-09-05
  • 1970-01-01
  • 2017-01-31
  • 1970-01-01
  • 2018-03-04
  • 2017-07-25
  • 2012-01-01
  • 1970-01-01
相关资源
最近更新 更多