Mike D
Mike D

Reputation: 365

grep multipe wildcards in string

Say I have a file that contains:

Release 2.1 OS: RHEL File: package_el6_2.0.1.1_x86_64.rpm
Release 2.1 OS: RHEL File: package_el6_2.0.1.1_i686.rpm
Release 2.1 OS: RHEL File: package_el7_2.0.1.1_x86_64.rpm
Release 2.1 OS: RHEL File: package_el7_2.0.1.1_i686.rpm

I want to grep and match lines that only contain 'package', 'el6', and 'x86_64'

How would I go about doing that on a one liner using grep? The line must match all three and grep shouldn't care about how many characters are in between. If there is a better tool for the job, I'm happy to use that instead.

I've tried the following and got no results:

grep package*el6*x86_64*

Seeing posts and documentation, I understand that * does not mean the same thing as it would in shell. I'm looking for the equivalent of it to use in regex. Hope this makes sense.

Upvotes: 9

Views: 8948

Answers (4)

John
John

Reputation: 3520

If they're guarenteed to be in order, then a simple grep:

grep "package.*el6.*x86_64" file.txt

would do it. If the items can be in any order, you can try a pipe:

cat file.txt | grep package | grep el6 | grep x86_64

will only show lines containing all three, but in any order

Upvotes: 0

Joan Esteban
Joan Esteban

Reputation: 1021

Not the best solution (in fact ineficient), but really easy to remember: join 3 greps

grep "package" | grep "el6" | grep "x86_64"

Upvotes: 4

Mad Physicist
Mad Physicist

Reputation: 114310

Your attempt is very close. * in shell glob terms is roughly equivalent to .* in regex terms. . means "any character" and * is means "repeated any number of times (including zero).

Your regex just needs . before each *. The trailing * is not necessary:

package.*el6.*x86_64

Here is a sample run with your input:

grep 'package.*el6.*x86_64' <<< "Release 2.1 OS: RHEL File: package_el6_2.0.1.1_x86_64.rpm
Release 2.1 OS: RHEL File: package_el6_2.0.1.1_i686.rpm
Release 2.1 OS: RHEL File: package_el7_2.0.1.1_x86_64.rpm
Release 2.1 OS: RHEL File: package_el7_2.0.1.1_i686.rpm"

Prints:

Release 2.1 OS: RHEL File: package_el6_2.0.1.1_x86_64.rpm

Upvotes: 13

connollyc4
connollyc4

Reputation: 155

You can use egrep

egrep 'package|el6|x86_64' name_of_file.txt

Upvotes: -3

Related Questions