Search text strings within files
The grep command is used to search plain-text data. It can search a single file or a whole directory of files for lines that contain the specified string. If a match is found, the line containing the string is printed on the screen. The syntax of the grep command is:
grep [OPTIONS] PATTERN FILE
Here is an example. Let’s say that we have a text file called textfile.txt with the following content:
To search textfile.txt for each occurence of the word text, we can use the following command:
Two occurences of the word text have been found in textfile.txt. The lines containing the word text have been printed on the screen.
Here is another example. To search the /home/pi/files/ directory (the working directory, in this case) for each occurence of the word text, we can use the following command:
As you can see from the output of the ls command, three files are stored in the /home/pi/files/ directory: file.txt, new-file.txt, and textfile.txt. The grep command has searched the whole working directory (hence the ./* string) and found and printed three matches of the word text.
The grep command is often used with commands that produce a lot of output, so you can sift through the output more easily. For example, to list all processes on the system, you can use the ps -A command:
This command produces a lot of output – hundreds of lines of text, in fact. We can use the grep command along with ps -A to find the specific process we are looking for. For example, to search for a process started by the nano text editor, we can use the ps -A | grep nano command:
Now we got only a single line of output – the line that contains the word nano. Note that the pipe (|) was used to send the output of the ps -A command to the grep command.