Junk Food for the Brain

Open Source and Awesomesauce :)

How to Search / Grep for More Than One Word at a Time

| Comments

A common question asked by linux beginners, so here’s how to do it.

Let’s say you need to search your /etc/passwd file for the users apache AND ftp. You could do it this way:-

[caption id=”attachment_141” align=”aligncenter” width=”516” caption=”The manual way of greppin'”]The manual way of greppin'[/caption]

Or being a sysadmin, you’d want to do it smarter.

Use the pipe symbol and the ‘-E’ switch with grep will solve this problem.

$ grep -E 'apache|ftp' /etc/passwd

[caption id=”attachment_142” align=”aligncenter” width=”516” caption=”Grepping 2 words at a time”]Grepping 2 words at a time[/caption]

While your there, lets add some colour to your output. This will help you see where exactly the pattern matches.

$ grep -E --colour 'apache|ftp' /etc/passwd

[caption id=”attachment_143” align=”aligncenter” width=”516” caption=”Grepping with some colour”]Grepping with some colour[/caption]

A final tip that will come in handy, especially when you’re grepping long config files is the line number. Adding a ‘-n’ to your grep will display the line number for the matching term. Notice how adding the ‘–colour’ option makes the line numbers coloured in green, while the actual matched word is coloured in red.

$ grep -En --colour 'apache|ftp' /etc/passwd

[caption id=”attachment_144” align=”aligncenter” width=”516” caption=”Grepping, now with colours and line numbers”]Grepping, now with
colours and line numbers[/caption]

Till another post, happy searching grepping.