0

I Have a csv file. It has multiple columns. I want to develop a shell script which prompts the use for a numerical value, find the closest match in the csv and print the header of the column. For example

        Apple       orange      grape      berry


1       1.3         1.9         0.4         1.756

2       2.1.        3.3         6.6         0.964

3      0.444        1.364       1.1         3.6

If the user input is 3.4, then the closest value is 3.3 and the output should be " This is Orange"

Any thoughts on how can I accomplish this. (FYI - CSV is pretty large file)

1

This is a little inelegant but works

read -p "Enter a value .... " t
awk -v test=$t 'NR==1{min=1000;for (i=1; i<=NF; i++) head[i]=$i}
    NR>1 && NF>0{for (i=2; i<=NF; i++){diff=($i<test)?(test-$i):($i-test); if (diff<min) {min=diff; item=i-1} }}
    END{ print "Closest to "test" is "head[item]}' file

Output

Closest to 3.4 is orange
  • thank you. Whats the min=1000 doing here. – MO12 Nov 25 '19 at 20:17
  • Just initialising the min value away from NULL and out of range of your likely matches. – bu5hman Nov 25 '19 at 20:21
  • this will not prompt the user for a input..right. can I make it prompt for an input value? – MO12 Nov 25 '19 at 20:28

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.