Programmer
Programmer

Reputation: 439

Comparing two files and printing lesser of two based on a key

Content of first file:

$cat File1
KEY1,4999
KEY2,3999
KEY3,5999
KEY4,10999

Content of second file:

$cat File2
KEY1,11905
KEY2,6872
KEY3,2393
KEY4,296360

Expected output file:

 KEY1,4999
 KEY2,3999
 KEY3,2393
 KEY4,10999

Searching for a one liner command to get the expected output. Requirement here is to print lesser number for each key, by comparing two files.

Upvotes: 2

Views: 41

Answers (2)

sjsam
sjsam

Reputation: 21965

awk can be your friend

$ cat f1
KEY1,4999
KEY2,3999
KEY3,5999
KEY4,10999
$ cat f2
KEY1,11905
KEY2,6872
KEY3,2393
KEY4,296360
$ awk -v FS="," '{$0=($2<$4)?$1 "," $2:$3 "," $4}1' <(paste -d',' f1 f2)
KEY1,4999
KEY2,3999
KEY3,2393
KEY4,10999

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Awk is "your friend" in this case:

awk 'BEGIN{ FS=OFS="," }
     NR==FNR{ a[$1]=$2; next }
     $1 in a{ 
         print $1, ($2 < a[$1]? $2 : a[$1]) 
     }' file1 file2

The output:

KEY1,4999
KEY2,3999
KEY3,2393
KEY4,10999

Upvotes: 3

Related Questions