首页 > 解决方案 > How to grep regex1 OR regex2?

问题描述

I would like to grep (on ubuntu18.04) a every line that fits the pattern that "at least one of two number is greater than 0".

I found infomation about '|' usage in regex but I see it does not work here.

One of tried option:

grep -E "Foo:[1-9]+ | Bar:[1-9]+" input

which returns:

Foo:1, Bar:1
Foo:0, Bar:1

and that is invalid cause it matches only Bar:[1-9]+

Input data:

Foo:1, Bar:0
Foo:1, Bar:1
Foo:0, Bar:1
Foo:0, Bar:0
Foo:55, Bar:0

Expected result in a solution:

Foo:1, Bar:0
Foo:1, Bar:1
Foo:0, Bar:1
Foo:55, Bar:0

标签: regexbashgrep

解决方案


The problem is the space after the number: there's no such space in your input data.

grep -E 'Foo:[1-9]|Bar:[1-9]'

gives the expected output.

It can be further simplified into

grep -E '(Foo|Bar):[1-9]'

Note that the + isn't needed: a number starting with 1-9 is already greater than 0 even if it's followed by 0 or by nothing at all.


推荐阅读