grep searches the input files for lines containing a match to a given pattern list. When it finds a match in a line, it copies the line to standard output (by default), or whatever other sort of output you have requested with options.
Though grep expects to do the matching on text, it has no limits on input line length other than available memory, and it can match arbitrary characters within a line. If the final byte of an input file is not a newline, grep silently supplies one. Since newline is also a separator for the list of patterns, there is no way to match newline characters in a text.
With the first command, user cathy displays the lines from /etc/passwd containing the string root.
Then she displays the line numbers containing this search string.
With the third command she checks which users are not using bash, but accounts with the nologin shell are not displayed.
Then she counts the number of accounts that have /bin/false as the shell.
The last command displays the lines from all the files in her home directory starting with ~/.bash, excluding matches containing history, so as to exclude matches from ~/.bash_history which might contain the same string, in upper or lower cases.
Now let's see what else we can do with grep, using regular expressions.
4.2.2. Grep and regular expressions
If you are not on Linux
We use GNU grep in these examples, which supports extended regular expressions. GNU grep is the default on Linux systems. If you are working on proprietary systems, check with the -V option which version you are using. GNU grep can be downloaded from http://gnu.org/directory/.
188.8.131.52. Line and word anchors
From the previous example, we now exclusively want to display lines starting with the string "root":
If this option is not used, all the lines from the file system table will be displayed.
184.108.40.206. Character classes
A bracket expression is a list of characters enclosed by "[" and "]". It matches any single character in that list; if the first character of the list is the caret, "^", then it matches any character NOT in the list. For example, the regular expression "" matches any single digit.
Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, "[a-d]" is equivalent to "[abcd]". Many locales sort characters in dictionary order, and in these locales "[a-d]" is typically not equivalent to "[abcd]"; it might be equivalent to "[aBbCcDd]", for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value "C".
Finally, certain named classes of characters are predefined within bracket expressions. See the grep man or info pages for more information about these predefined expressions.