Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep command with multiple patterns

Tags:

linux

grep

Hi i am currently use this to grep:

$ grep -nri --exclude-dir=DELIVERY_REL "xxxxxx\.h" --colour --include=*.{c,h}

I am trying to fine tune the search results of my grep to include multiple patterns. I have tried multiple ways recommended on stack-overflow on similar questions, but to no avail. What i need to grep:

xxxxxx.h and #include or xxxxxx.h and # include (with a space)
like image 393
Kenny Quah Kok Siong Avatar asked Dec 22 '25 05:12

Kenny Quah Kok Siong


2 Answers

To include multiple pattern to grep command you need option "-e".

For example you can include pattern "pattern1" e "pattern2" in this way:

grep -e "pattern1" -e "pattern2" filename.ext
like image 97
Zig Razor Avatar answered Dec 23 '25 20:12

Zig Razor


OR: To search for lines that match regex A or B specify each of the regexes with a preceding -e option in a single grep command: grep -e A -e B. Alternatively, use the alternation operator inside a single regex: grep -E 'A|B'

AND: To print only lines that match regex A and B chain two grep searches: grep A | grep B. Alternatively, list all possible orders in which the regex can match in a single regex: grep -E 'A.*B|B.*A'

For your specific case you could use

grep 'xxxxxx\.h' | grep -E '# ?include'

Here the ? after the space means that the space is optional.
# ?include is equivalent to #include|# include.

like image 38
Socowi Avatar answered Dec 23 '25 20:12

Socowi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!