Search for text strings using grep

The grep tool is used to locates files by scanning their content. You can search a single file or a whole directory of files. By default, grep prints the matching line of text. The syntax is:

grep [OPTIONS] PATTERN FILE

For example, if we want to search the file bobs_file.txt for each occurence of the word bob, we can use the following command:

linux grep example

Here is another example. If we want to search the directory /home/bob for each occurence of the word bob, we can use the following command:

linux grep search for files

In the picture above we can see that there are two occurrences of the word bob in the files inside the /home/bob directory. The -r option specifies that the subdirectories will also be searched. Note that the grep command has listed the filename and the line of the text containing the keyword bob.

grep is most commonly used in conjunction with commands that produce a lot of output, so you can sift through that output for the lines that are important to you. For example, suppose that we would like to display the members of the group cdrom. We can do this by typing the cat /etc/group command, which will display all the groups and their members on the system:

linux cat etc groups

We can then scroll through the output and find the cdrom group and its members. Or, we could pipe the output to the grep command and display only the lines of text that contain the word cdrom:

linux pipe grep

Here is an another example of the usefulness of the grep command. We can use the ps -A command to display all running processes on the system:

linux ps A option

The ps -A command produces a lot of output. If we know the exact name of the process, we can pipe the output to the grep command:

linux grep top

In the picture above you can see that there are two instances of the top program running.

By default, grep searches the text in a case-sensitive way. You can do case-insensitive searches with the -i option.

Subscribe to our Newsletter

Like us on Facebook

top
Geek University 2019