I have a text file with the following format:

Item A,10-20
Item B,21-30
Item C,31-60
Item D,61-120

how can I search the file with any number and I get the line returned that includes the number given by the range in the second field.

so lets say I search for 33 I get Item C
if I search for 100 I get Item D and so on...

(my question does not focus on the field separation but rather on matching the line within the range, so if I would get the whole line displayed this would be fine)

2 Answers 2


Shorter awk:

$ awk -F'[,-]' -v s=11 's>=$2 && s<=$3' file1
Item A,10-20

$ awk -F'[,-]' -v s=100 's>=$2 && s<=$3' file1
Item D,61-120

$ awk -F'[,-]' -v s=61 's>=$2 && s<=$3' file1
Item D,61-120

As mentioned in comments if you want to print only the labels just add {print $1} in the end:

$ awk -F'[,-]' -v s=61 's>=$2 && s<=$3{print $1}' file1
Item D
  • 1
    ok, you convinced me with the shortness :-)
    – nath
    Jan 13, 2018 at 23:33
  • 2
    Ah, I forgot awk can use a regex as a field separator. You could still add { print $1} to just print the label.
    – ilkkachu
    Jan 13, 2018 at 23:33

Something like this?

$ awk -vval=33  -F, '{ label = $1; split($2, limits, "-"); } 
                     limits[1]+0 <= val && val <= limits[2]+0 {print label} ' < input
Item C

We just split on , to separate the label, then split on - to separate the low and high limits. +0 to force comparison as numbers.


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.