Advertisement
Guest User

Untitled

a guest
Dec 11th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. 1
  2. 2
  3. 3
  4.  
  5. 2 2 2 1 2
  6. 3 6 1 2 4
  7. 4 1 1 2 3
  8. 6 3 3 3 4
  9.  
  10. #!/usr/local/bin/awk -f
  11.  
  12. {
  13. ## FNR is the line number of the current file, NR is the number of
  14. ## lines that have been processed. If you only give one file to
  15. ## awk, FNR will always equal NR. If you give more than one file,
  16. ## FNR will go back to 1 when the next file is reached but NR
  17. ## will continue incrementing. Therefore, NR == FNR only while
  18. ## the first file is being processed.
  19. if(NR == FNR){
  20. ## If this is the first file, save the values of $1
  21. ## in the array n.
  22. n[$1] = 0
  23. }
  24. ## If we have moved on to the 2nd file
  25. else{
  26. ## If the 3rd field of the second file exists in
  27. ## the first file.
  28. if($3 in n){
  29. ## Add the value of the 5th field to the corresponding value
  30. ## of the n array.
  31. n[$3]+=$5
  32. }
  33. }
  34. }
  35. ## The END{} block is executed after all files have been processed.
  36. ## This is useful since you may have more than one line whose 3rd
  37. ## field was specified in the first file so you don't want to print
  38. ## as you process the files.
  39. END{
  40. ## For each element in the n array
  41. for (i in n){
  42. ## print the element itself and then its value
  43. print i,":",n[i];
  44. }
  45. }
  46.  
  47. $ chmod a+x foo.awk
  48. $ ./foo.awk file1 file2
  49. 1 : 7
  50. 2 : 2
  51. 3 : 4
  52.  
  53. awk '
  54. (NR == FNR){n[$1] = 0; next}
  55. {if($3 in n){n[$3]+=$5}}
  56. END{for (i in n){print i,":",n[i]} }' file1 file2
  57.  
  58. awk '
  59. NR == FNR {n[$3] += $5; next}
  60. {print $1 ": " n[$1]}' file2 file1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement