Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep multipe wildcards in string

Tags:

linux

grep

shell

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.

like image 740
Mike D Avatar asked Aug 31 '16 19:08

Mike D


2 Answers

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
like image 84
Mad Physicist Avatar answered Oct 19 '22 03:10

Mad Physicist


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

grep "package" | grep "el6" | grep "x86_64"
like image 4
Joan Esteban Avatar answered Oct 19 '22 02:10

Joan Esteban