Merinoide
Merinoide

Reputation: 71

Filter with grep a value greater and less than range

I have a csv with this data:

0,M,19,finnish,english swedish german 
9,M,30,urdu,english 
122,F,26,finnish,english swedish german
83,M,20,finnish,english french swedish 
44,F,20,finnish,english swedish 
10,F,29,finnish,english

And I need a filter using GREP than take user value (first column) great than 10 and less than 99.

This is my best movement:

cat demographic_info.csv | grep -e "1[0-9]*" 

Upvotes: 1

Views: 5803

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

Assuming you want to match numbers from 10 to 99 exclusively (that is, 11 to 98 inclusively), you can use

grep -E '^(1[1-9]|[2-8][0-9]|9[0-8]),' file

The numeric range pattern is automatically generated at How to match numbers between X and Y with regexp?, I just needed to remove ?: as POSIX ERE does not support non-capturing groups.

However,

awk -F\, '$1 < 99 && $1 > 10' file

looks a much better fit for this task. It uses a comma as a field separator, and checks if the first field value is less than 99 and bigger than 10, and outputs only those lines.

See an online demo:

#!/bin/bash
s='0,M,19,finnish,english swedish german 
9,M,30,urdu,english 
122,F,26,finnish,english swedish german
83,M,20,finnish,english french swedish 
44,F,20,finnish,english swedish 
10,F,29,finnish,english'
awk -F\, '$1 < 99 && $1 > 10' <<< "$s"
echo "---"
grep -E '^(1[1-9]|[2-8][0-9]|9[0-8]),' <<< "$s"

Output:

83,M,20,finnish,english french swedish 
44,F,20,finnish,english swedish 
---
83,M,20,finnish,english french swedish 
44,F,20,finnish,english swedish 

Upvotes: 5

Related Questions