How to Search for an Exact String With GREP

GREP is one of those simple UNIX programs that you can’t live without if you do any kind of systems administration of an operating system based on UNIX such as Linux or Mac OS X. If you need to search for an exact string and NOT just a substring, all you have to do is specify the “-w” command line switch. For example, say you wanted to search for the string “username” in a text file named “login.php” that contains the following lines:

username = "foo";
groupusername = "myGroupUserName";
defaultusername = "defaultUser";

If you try the command:

grep “username” login.php

all of the lines in the file would be returned since they all contain the substring “username” somewhere in the line.

locahost ~: grep "username" login.php
username = "foo";
groupusername = "myGroupUserName";
defaultusername = "defaultUser";

However if you specify the “-w” command line switch, only the first line will be returned:

localhost ~: grep -w "username" login.php
username = "foo";

Terminal