Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two file numeric comparison in awk

Tags:

linux

awk

I'm trying to compare the contents of two files, both of which are just a single column of numbers, i.e.

File1:

1.2
2.6
3.4
4.7
5.3

File2:

5.1
4.8
3.2
2.5
1.6

The output should just be the number of lines in file1 that are greater than the corresponding line in file2; so in this case it'd just be

3

like image 746
Ian R Avatar asked Sep 13 '26 05:09

Ian R


2 Answers

awk single process can do that job:

awk 'NR==FNR{a[NR]=$0;next}a[FNR]>$0{i++}END{print i}' file1 file2

outputs:

3

EDIT

by reading JonathanLeffler and steveha's comments, I would add another solution, to avoid to save a monster file into memory. still single awk process:

 awk '{getline x < "file2"}$0>x{i++}END{print i}' file1

outputs:

3
like image 182
Kent Avatar answered Sep 15 '26 19:09

Kent


Try using paste followed by awk

paste file1 file2 | awk '$1>$2 {i++} END {print i}'

Output:

3
like image 32
jkshah Avatar answered Sep 15 '26 20:09

jkshah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!