The grep command stands for “global regular expression print”, and it is one of the most powerful and commonly used commands in Linux.
Grep searches one or more input files for lines that match a given pattern and writes each matching line to standard output. The syntax for the grep command is as follows:
$ grep [OPTIONS] PATTERN [FILE...]
Search for a String in Files: to display all the lines containing the string bash from the /etc/passwd file, you would run the following command:
Example:
$ grep bash /etc/passwd
root:x:0:0:root:/root:/bin/bash
apple:x:1000:1000:apple:/home/apple:/bin/bash
If the string includes spaces, you need to enclose it in single or double quotation marks:
Example:
$ grep "Gnome Display Manager" /etc/passwd
Invert Match: To display the lines that do not match a pattern, use the -v option. For example, to print the lines that do not contain the string nologin you would use:
Example:
$ grep -v nologin /etc/passwd
root:x:0:0:root:/root:/bin/bash
colord:x:124:124::/var/lib/colord:/bin/false
git:x:994:994:git daemon user:/:/usr/bin/git-shell
apple:x:1000:1000:apple:/home/apple:/bin/bash
Recursive Search: To recursively search for a pattern, invoke grep with the -r option (or --recursive). When this option is used grep will search through all files in the specified directory, skipping the similar links that are encountered recursively.
Here is an example showing how to search for the string apple.com in all files inside the /etc directory:
Example:
$ grep -r apple.com /etc
/etc/hosts:127.0.0.1 node2.apple.com
/etc/nginx/sites-available/apple.com: server_name apple.com www.apple.com;
If you use the -R option (or –dereference-recursive), grep will follow all symbolic links including the similar ones as well:
Example:
$ grep -R apple.com /etc
/etc/hosts:127.0.0.1 node2.apple.com
/etc/nginx/sites-available/apple.com: server_name apple.com www.apple.com;
/etc/nginx/sites-enabled/apple.com: server_name apple.com www.apple.com;
Notice the last line of the output below. That line is not printed when grep is invoked with –r because files inside the Nginx’s sites-enabled directory are symlinks to configuration files inside the sites-available directory.
Show Only the Filename: To print only the names of files containing the matched pattern, use the -l ( or --files-with-matches) option.
The command below searches through all files ending with .conf in the current working directory and prints only the names of the files containing the string apple:
Example:
$ grep -l apple *.conf
tmux.conf
haproxy.conf