How to use grep with multiple patterns?

I am trying to grep a variable with multiple lines with multiple patterns

below is the pattern list in a variable called "grouplst", each pattern is speerated by "|"

grouplst="example1|example2|example3|example4|example5|example6|example7"

I need to use the patterns above to grep a variable with multiple lines inside. the variable with the multiline content is called "nidgrps", content of the variable is below

memberof: example1_samplegroup
memberof: exampleone_samplegroup
memberof: example2_samplegroup
memberof: example3_samplegroup
memberof: examplefake_samplegroup
memberof: example4_samplegroup
memberof: examplefalse_samplegroup

I tried using egrep but it didnt work, my code is below

cat $nidgrps | egrep -i $grouplist >> $rptfile

"rptfile" is where I want the greped output to go

Thank You

When you have code that isn't working, it always helps us help you if you show us the exact diagnostics that are printed when you run your code, show us any other output that you get, and tell us what operating system and shell you're using.

Assuming that the variable nidgrps has been initialized to the name of the file containing the data you want to process, that the variable rptfile has been initialized to the string rptfile , that you are trying to perform a case-insensitive match, that you want to add the matched text to the end of the current contents of the file named rptfile rather than replace its existing contents, and that you are using a shell that uses basic Bourne shell syntax; you would have succeeded if you had quoted your variables appropriately.

But, in addition to that, there is no need for cat in this pipeline; using it just slows you down and consumes system resources needlessly. Try:

egrep -i "$grouplist" "$nidgrps" >> "$rptfile"

Consider the following... it works. I'm thinking that just like my case below your nidgrps maybe is a string inside a variable?? So you'd use echo instead of cat??

nidgrps='memberof: example1_samplegroup
memberof: exampleone_samplegroup
memberof: example2_samplegroup
memberof: example3_samplegroup
memberof: examplefake_samplegroup
memberof: example4_samplegroup
memberof: examplefalse_samplegroup'

grouplst="example1|example2|example3|example4|example5|example6|example7"

echo "${nidgrps}" | egrep -i "${grouplst}"
1 Like