使用shell脚本比较2个文件中的分号分隔数据

时间:2009-11-17 09:02:56

标签: perl unix shell

我有一些数据(以分号分隔),文本文件temp1中有近240行。 temp2.txt存储204行数据(以分号分隔)。

我想:

  1. field1对两个文件中的数据进行排序,即每行中的第一个数据字段。
  2. 比较两个文件中的数据,并重定向单独文件中不相等的行。
  3. 示例数据:

    temp1.txt
    1000xyz400100xyzA00680xyz0;19722.83;19565.7;157.13;11;2.74;11.00
    1000xyz400100xyzA00682xyz0;7210.68;4111.53;3099.15;216.95;1.21;216.94
    1000xyz430200xyzA00651xyz0;146.70;0.00;0.00;0.00;0.00;0.00
    
    temp2.txt
    1000xyz400100xyzA00680xyz0;19722.83;19565.7;157.13;11;2.74;11.00
    1000xyz400100xyzA00682xyz0;7210.68;4111.53;3099.15;216.95;1.21;216.94
    

    我正在使用的排序命令:

    sort -k1,1 temp1 -o temp1.tmp
    sort -k1,1 temp2 -o temp2.tmp
    

    如果有人能告诉我如何将缺失/不匹配的行重定向到两个单独的文件进行分析,我将不胜感激。

4 个答案:

答案 0 :(得分:3)

尝试

cat temp1 temp2 | sort -k1,1 -o tmp
# mis-matching/missing rows:
uniq -u tmp
# matching rows:
uniq -d tmp

答案 1 :(得分:1)

请看the comm command

答案 2 :(得分:1)

您需要http://www.pixelbeat.org/cmdline.html#sets

所述的差异
sort -t';' -k1,1 temp1 temp1 temp2 | uniq -u > only_in_temp2
sort -t';' -k1,1 temp1 temp2 temp2 | uniq -u > only_in_temp1

注意:

  • 如果您只想比较特定字段
  • ,请使用join而不是uniq,如上面的链接所示
  • 如果第一个字段是固定宽度,那么您不需要-t';' -k1,1上面的参数

答案 3 :(得分:0)

使用gawk,并输出file1中不在file2中的行

awk -F";" 'FNR==NR{  a[$1]=$0;next }
( ! ( $1 in a)  ) {  print $0 > "afile.txt" }' file2 file1

将file2和file的顺序与file2中不在file1中的输出行交换