The
grep
command is a text filter that will search input and return lines which contain a match to a given pattern.grep [OPTIONS] PATTERN [FILE]
Follow Along
Use the following command to switch to the Documents
directory:
sysadmin@localhost:~$ cd ~/Documents
If the example below fails, repeat the example from Section 11: Copying Files:
sysadmin@localhost:~/Documents$ cp /etc/passwd .
For example, the passwd
file we previously copied into the Documents
directory contains the details of special system accounts and user accounts on the system. This file can be very large, however the grep
command can be used filter out information about a specific user, such as the sysadmin
user. Use sysadmin
as the pattern argument and passwd
as the file argument:
sysadmin@localhost:~/Documents$ grep sysadmin passwd sysadmin:x:1001:1001:System Administrator,,,,:/home/sysadmin:/bin/bash
The command above returned the line from the passwd
which contains the pattern sysadmin
.
Note
This line is the /etc/passwd
entry pertaining to the user sysadmin
and provides information that is beyond the scope of this course.
The example above uses a simple search term as the pattern, however grep
is able to interpret much more complex search patterns.
Regular expressions
Regular expressions have two common forms: basic and extended. Most commands that use regular expressions can interpret basic regular expressions. However, extended regular expressions are not available for all commands and a command option is typically required for them to work correctly.
The following table summarizes basic regular expression characters:
Basic Regex Character(s) | Meaning |
---|---|
. | Any one single character |
[ ] | Any one specified character |
[^ ] | Not the one specified character |
* | Zero or more of the previous character |
^ | If first character in the pattern, then pattern must be at beginning of the line to match, otherwise just a literal ^ |
$ | If last character in the pattern, then pattern must be at the end of the line to match, otherwise just a literal $ |
The following table summarizes the extended regular expressions, which must be used with either the egrep
command or the -E
option with the grep
command:
Extended Regex Character(s) | Meaning |
---|---|
+ | One or more of the previous pattern |
? | The preceding pattern is optional |
{ } | Specify minimum, maximum or exact matches of the previous pattern |
| | Alternation - a logical "or" |
( ) | Used to create groups |
Only basic regular expressions have been covered here.