0

I have the following two text files:

fruits.txt

nectarine      strawberry
orange         peach
grape          apple
mango          watermelon

numbers.txt

strawberry    57
apple         48
mango         40
peach         44
watermelon    60
nectarine     46
orange        72   
grape         39

In fruits.txt I want to keep only one of the 2 fruits per line. The one removed should be the one with the higher corresponding number (c.f. numbers.txt). The output would look like:

nectarine
peach
grape
mango

How could I proceed to achieve this in bash?

2 Answers2

4

You may use this awk command:

awk 'FNR == NR {num[$1]=$2; next} {
print (num[$1] < num[$2] ? $1 : $2)}' numbers.txt fruits.txt

nectarine
peach
grape
mango
anubhava
  • 761,203
  • 64
  • 569
  • 643
3

You can use read and while loop. For example:

#!/bin/bash

# read numbers.txt into associate array
declare -A a
while read k v; do
    a[$k]=$v
done < numbers.txt

# process the fruits.txt
while read l r; do
    (( a[$l] > a[$r] )) && l=$r
    echo $l
done < fruits.txt

will give the desired output

DaBler
  • 2,695
  • 2
  • 26
  • 46