2

top1

1,facebook.com
2,google.com
3,youtube.com
4,yahoo.com
5,wikipedia.org
6,baidu.com
7,live.com
8,amazon.com
9,qq.com
10,twitter.com

top2

1,facebook.com
2,google.com
3,youtube.com
4,yahoo.com
5,baidu.com
6,wikipedia.org
7,live.com
8,qq.com
9,amazon.com
10,twitter.com

diff -u  /Users/stofke/Desktop/top2a.csv /Users/stofke/Desktop/top1a.csv |
  sed -n '1,2d;/^[-+]/p' |
  sort --field-separator=',' --key=2 

+9,amazon.com
-8,amazon.com
+5,baidu.com
-6,baidu.com
+8,qq.com
-9,qq.com
+6,wikipedia.org
-5,wikipedia.org

But I actually need this:

 +1, amazon.com
 -1  baidu.com
 -1  qq.com
 +1  wikipedia.org

I don't know how to do that last step

(I would also need to calculate the % wise decline or raise)

Adding | paste -d, - -

gets me this

+9,amazon.com,-8,amazon.com
+5,baidu.com,-6,baidu.com
+8,qq.com,-9,qq.com
+6,wikipedia.org,-5,wikipedia.org
1
  • Diff doesn't do this. You'll need to write a small script that does it. Jan 20 '13 at 17:08
4

Using awk

awk -F, '
    NR == FNR {n[$2] = $1; next}
    {n[$2] -= $1}
    END {for (k in n) if (n[k] != 0) printf " %2d  %s\n",n[k],k}
' top1 top2

outputs

 -1  amazon.com
  1  qq.com
 -1  wikipedia.org
  1  baidu.com

order not guaranteed.

1
  • I bet it's good but it's too hard for me to read it and understand it. Anyway thank you very much for this answer
    – Stofke
    Jan 20 '13 at 21:05
2

You could also consider an approach using join since you want sorted output in the end. Like:

join -t, -j2 <(sort -t, -k2 file1) <(sort -t, -k2 file2) |
   awk -F, '{n=$3-$2; if (n) print n, $1}'
1
  • I like this answer, it's easy to read and does it well
    – Stofke
    Jan 20 '13 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.