Filtering Input

Grep ( The Weapon)

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:
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 grepcommand can be used filter out information about a specific user, like 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
​⁠​‌‌⁠⁠⁠⁠​
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.

Comments