The grep command (which stands for Global Regular Expression Print) is one of the most powerful and frequently used utilities in Linux. It allows you to search for specific text, words, or patterns inside files quickly from the command line. Whether you are analyzing log files or searching through code, mastering grep is an essential Linux skill.
Basic Syntax
The fundamental structure of the grep command is:
grep [options] "pattern" [file]
You define what you are looking for (the pattern) and where you want to look (the file).
Common Examples and Use Cases
1. Perform a Basic Search
To find all lines containing a specific word in a text file, use the command without any options. It is good practice to wrap your search term in quotes.
grep "error" serverlog.txt
2. Make the Search Case-Insensitive
By default, grep is case-sensitive. If you want to search for “linux” and also match “Linux” and “LINUX”, use the -i option.
grep -i "linux" document.txt
3. Search for Whole Words Only
If you search for “is”, grep will also return words that contain those letters, such as “This” or “mistake”. To restrict the search to exact, isolated words, use the -w option.
grep -w "is" document.txt
4. Display Line Numbers
When searching through large configuration or code files, it is helpful to know exactly where the match is located. Use the -n option to print the line number alongside the matching text.
grep -n "database_url" config.php
5. Invert the Match (Exclude Lines)
Sometimes you want to see everything except a specific term. Use the -v option to display all lines that do not contain the specified pattern.
grep -v "success" serverlog.txt
6. Search Recursively Through a Directory
Instead of searching a single file, you can search through an entire directory and all its subdirectories to find which files contain your text. Use the -r option.
grep -r "API_KEY" /var/www/html/
7. Count the Number of Matches
If you only want to know how many lines contain your search term, rather than reading the lines themselves, use the -c option.
grep -c "failed login" auth.log
You can combine these options as needed. For example, grep -in "error" file.txt will perform a case-insensitive search and display the line numbers.