Skip to Content

grep Command in Linux

The grep command in Linux is a powerful command-line utility used for searching text files or input streams for lines that match a specific pattern.

What is grep Command in Linux?

grep searches through text - usually files or command outputs looking for lines that match a given pattern. It then prints the matching lines to the terminal.

Basic Syntax of grep Command :

grep [options] pattern [file...]


Example of grep Command in Linux

1. Search for a Word in a File

grep "error" logfile.txt

🔹 Finds all lines in logfile.txt that contain the word "error".

2. Case-Insensitive Search

grep -i "error" logfile.txt

🔹 Matches "Error", "ERROR", "error", etc.

3. Search Recursively in Directories

grep -r "main()" .

🔹 Searches the current directory and subdirectories for the pattern "main()".

4. Count the Number of Matches

grep -c "failed" logfile.txt

🔹 Returns the number of lines that contain "failed".

5. Display Line Numbers

grep -n "timeout" config.txt

🔹 Shows the line numbers where "timeout" occurs.


Useful Options in grep Command

OptionDescription
-iCase-insensitive search
-rRecursive search through directories
-cCount matching lines
-nShow line numbers
-lList only filenames with matches
-wMatch whole words
-AShow A lines after a match
-BShow B lines before a match
-CShow C lines of context (before & after)

Example : Showing Context Around a Match

grep -C 2 "error" logfile.txt

🔹 Displays 2 lines before and after each matching line.


Advanced grep command usage : Regular Expressions

grep supports regular expressions, allowing for more flexible pattern matching.

Example: Match lines that start with "Failed"

grep "^Failed" file.txt

Example: Match lines ending in ".log"

grep "\.log$" file.txt


Combining grep with Other Commands

grep becomes even more powerful when combined in pipelines:

Find errors in real-time logs:

tail -f syslog.log | grep "ERROR"

Search for users with /bin/bash in /etc/passwd:

cat /etc/passwd | grep "/bin/bash"

Related Commands

  • egrep: Extended grep (now deprecated, use grep -E)
  • fgrep: Fixed-string grep (use grep -F)
  • zgrep: For searching in compressed .gz files


grep is very useful in pattern matching and text filtering on the command line as whether you're troubleshooting logs, analyzing data, or scripting automation tasks , understanding grep will help you.


Back

Check out these tutorials :