1

I have two files

File1
A 10
B 6
...

File2 
C 12 
D 3
...

So I am trying to write an awk script where comparison is made on the basis of the second column and for the highest value, the entire line is printed out. In this case: Answer will be:

C 12
A 10
...

I have the record for twenty rows in each file. So, I need to print the top twenty from the entire two files. I am really stuck with this.

  • I noticed your comments on the answers; because we have some smart, quick-answering people on the site, you need to take care with your question so that it says what you have and what you need. The current Answerers would be right to ask you to open a new/different question with new/different requirements. – Jeff Schaller Nov 3 '17 at 20:53
2

I wouldn't use awk here:

cat all your files | sort -k2,2nr | head -n 20
  • Thank. So, simply solved it! But In case If I need to know from which file the highest value is coming from.. then? – Bandana Nov 3 '17 at 20:12
  • Replace cat file ... with grep -H '^' file ... – glenn jackman Nov 3 '17 at 20:57
0

GNU awk alternative solution:

Sample file1 and file2 contents:

$ head file[12]
==> file1 <==
A 1
B 2
C 4
D 10
E 14
F 5
G 7

==> file2 <==
H 11
I 20
J 41
K 12
L 55
M 14
N 80
O 100

The job:

awk -v top=5 'BEGIN{ PROCINFO["sorted_in"]="@val_num_desc" }
             { a[$1]=$2 }
             END{ for(i in a) { print i,a[i]; if(++c==top) break } }' file1 file2
  • -v top=5 - variable pointing to the number of top records to be printed

The output:

O 100
N 80
L 55
J 41
I 20
  • Nice. I'd put $0 as the array key, in case $1 is not unique – glenn jackman Nov 3 '17 at 20:02
  • Thank you. I also need to know from which file. In my case, there are 6 files. – Bandana Nov 3 '17 at 20:11

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.