Using range in grep

2019-09-03 07:55发布

The following command does work as expected.

grep -B3 'Max_value: 127' proc_*.*

But I need to compare the number of Max Value and find if it is between 127 and 200.

grep -B3 'Max_value: (>127 and <200)' proc_*.*

标签: sed awk grep
4条回答
三岁会撩人
2楼-- · 2019-09-03 08:36

Use awk for your task. The reason being, its easier to compare numbers than manually inputting character classes. What if you need to check a whole wider range.?

$ cat file
0
1
2
3
Max_value: 127
a
b
c
d
Max_value: 130
blah1
blah2
blah3
blah4
Max_value: 200
Z
Y
W
X
Max_value: 2001

$ awk -F":" '{a[NR%3]=$0} /Max_value/&&$2>=127&&$2<=200 {for(i=NR+1;i<=NR+3;i++)print a[i%3] }' file
2
3
Max_value: 127
c
d
Max_value: 130
blah3
blah4
Max_value: 200
查看更多
forever°为你锁心
3楼-- · 2019-09-03 08:43
grep 'Max_value:' proc_*.* | awk ' $2 ~ /[0-9]{3}$/ && $2 > 127 && $2 < 200 '

edit: adding check for (3 digit numeric)$.

查看更多
孤傲高冷的网名
4楼-- · 2019-09-03 08:43
grep -B3 -E '^Max_value: (12[789]|1[3-9][0-9]|200)$' proc_*.*

The -E uses an extended mode that allows alternation without escaping. Otherwise:

grep -B3 '^Max_value: \(12[89]\|1[3-9][0-9]\)$' proc_*.*
查看更多
叼着烟拽天下
5楼-- · 2019-09-03 08:50

I bet you're better of with awk in this scenario, but since you asked for a grep solution:

$ cat values.txt 
Max_value: 123
Max_value: 600
Max_value: 126
Max_value: 128
Max_value: 130
Max_value: 111
Max_value: 199
Max_value: 200
Max_value: 155
Max_value: 250
$ grep -E "Max_value: (12[89]|1[3-9][0-9])" values.txt 
Max_value: 128
Max_value: 130
Max_value: 199
Max_value: 155
查看更多
登录 后发表回答