Home > Software design >  Bash: compare if a value is contained within an interval
Bash: compare if a value is contained within an interval

Time:02-16

I got a text file which is tab separated and contains 2 columns like this:

1227637    1298347
1347879    1356788
1389993    1399847
...        ...

Now I got some values from an analysis and I'd like to check if these values are contained in my text file intervals. For example if I have 1227659, which is contained in the first interval, I'd like the bash-script to print to std out something like:

1227659 is contained between 1227637 and 1298347

Thanks.

CodePudding user response:

How about:

awk -v x=1227659 '
  $1<x && x<$2 {print x, "is contained between", $1, "and", $2}
' intervals.txt
1227659 is contained between 1227637 and 1298347

If you want any end of the interval to be interpreted as inclusive, change < to <= accordingly. If you want to stop after the first match (makes only sense if the intervals can overlap), add ; exit before the closing curly brace }.

  • Related