2

price.txt file has two columns:(name and value)

Mary 134
Lucy 56
Jack 88
Marissa 37
Emily 85
Antony 99

range.txt file also has two columns:(fruit and value)

apple 57
banana 62
orange 88
blueberry 98

The second column of range.txt is ordered (from minimum to maximum)

My aim is to extract rows of price.txt of which the values are within the range of values (57 - 98) in range.txt file.

The expected result is as follows:

Jack 88
Emily 85

I try to solve this by using the following code, but I don't know how to select the first line and the last line of the specific column. The unclear parts of the code are between asterisks (**...**):

awk 'FNR == NR {value=$2; **low=??; high=??**; next} 
     {if ($2>=**low** && $2<=**high** ) print $0}' range.txt price.txt
3
  • Thank you @don_crissti But I don't know how to get the low value. It seems that the $2 of the first file is the maximum value (98).
    – lightsnail
    Sep 14, 2016 at 22:16
  • awk 'FNR == NR {high=$2; if(NR==1) low=high; next} {if ($2>=low && $2<=high ) print $0}' range.txt price.txt
    – lightsnail
    Sep 14, 2016 at 22:22
  • It works! Big Big Thanks! @don_crissti O(∩_∩)O Nice ending of today's work!
    – lightsnail
    Sep 14, 2016 at 22:26

1 Answer 1

1
awk 'FNR == NR {high=$2; if(NR==1) low=high; next} 
     {if ($2>=low && $2<=high ) print $0}' range.txt price.txt

When FNR == NR, it will read the range.txt file, here we assign the second column of range.txt file to high, and use if(NR==1) low=high to assign the first value of high to low, then we can use these values in the next if sentence. And the print $0 will print out the rows meeting the condition.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .