As you can see, the numbers are in order from smallest to greatest, however, some numbers are missing. Say a user provides a number that is missing in the range of numbers. How do I grab the closest number in that range to what the user provided?
like say the user provided the number 39. From looking at the above range, you can see that the number 35 doesn't exist. So, how do I know to pick the closest number to 39 that does exist in the range? The closest numbers to 39, in the above range, are 30 and 48. How can I do this in a bash shell script?
I just put the logic in for printing out 30, based on user input of 39, work on the logic and you can get it to print 48 or whatever the next number is. Off course the script needs improvement in terms of error checking, checking if user did supply $1 etc., left as an exercise for OP :). It will go up and down 100 numbers only, which can be tweaked.
# cat /tmp/23.sh
#!/usr/bin/bash
>/tmp/results
IFS=" ,"
OFS="\n"
v=$1
for i in `cat /tmp/90`
do
for x in {0..100}
do
t=`echo "$v-$x"|bc`
if [[ $t = $i ]]
then
echo $i >> /tmp/results
fi
done
done
echo "`tail -1 /tmp/results`"
That is a useless use of cat. If the file is too large it may silently op off the end bit before feeding it into your program. Since you're using BASH, you can just do: