I have few lines in my text file as below. I want to grep all the lines which have patterns like :100, :101 and :102 up to :199 . How to get those lines instead of searching like this. :100\|:101\|:102...

abcd fhijk:123
abcd fhijk:124
abcd fhijk:174
abcd fhijk:225
  • 1
    May I ask the relevance of the vim tag on this question? – Kusalananda Nov 3 '18 at 12:11

Assuming your numbers are always positive integers with no unit, unary plus signs or other decorations.

Regular expressions aren't great for comparing numbers, but if you see your input data as two :-separated columns, it would be easier to handle it with awk:

awk -F ':' '$2 >= 100 && $2 <= 199' <file

This would compare the second :-separated field in the data to 100 and 199 and print the complete line if the number is within the given range.

It's also doable with grep, but not as flexible:

grep ':1[0-9][0-9]$' <file

The expression [0-9] matches a single character between 0 and 9. The $ anchors the expression to the end of the line.

If you wanted to match lines with the numbers 100 to 250, you would just change 199 in the awk code to 250, but with a regular expression you would have to come up with

grep -E ':(1[0-9][0-9]|2[0-4][0-9]|250)$' <file

Here, the three parts of the parenthesis matches numbers from 100 to 199, then from 200 to 249, and lastly 250. (I say "numbers", but regular expressions always operate on strings).

  • Note: the awk one would match on 00120, any:1000% and may or may not match on 0.1e3 or any:1000\r depending on the awk implementation, which may or may not be a problem depending on how tamed the user input is. See also awk -F ':' '$2+0 >= 100 && $2+0 <= 199' to force numeric conversion of the 2nd field. – Stéphane Chazelas Nov 3 '18 at 12:06

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.