0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use grep Command in Linux: Syntax and Examples

The grep command in Linux searches for specific text patterns inside files or input streams. Use grep 'pattern' filename to find lines containing the pattern in a file. It helps quickly locate text in logs, scripts, or any text data.
📐

Syntax

The basic syntax of grep is:

  • grep [options] 'pattern' filename

Here, pattern is the text or regular expression you want to find, and filename is the file to search in. Options modify how grep works, like ignoring case or showing line numbers.

bash
grep [options] 'pattern' filename
💻

Example

This example searches for the word error in a file named log.txt. It prints all lines containing error.

bash
echo -e "info: start\nerror: failed to load\ninfo: done" > log.txt
grep 'error' log.txt
Output
error: failed to load
⚠️

Common Pitfalls

Common mistakes include:

  • Not quoting the pattern, which can cause shell expansion issues.
  • Forgetting that grep is case-sensitive by default.
  • Using grep without specifying a file or input.

Always quote your pattern and use -i to ignore case if needed.

bash
grep error log.txt
# May miss 'Error' or 'ERROR'
grep -i 'error' log.txt
# Finds 'error', 'Error', 'ERROR'
📊

Quick Reference

OptionDescription
-iIgnore case distinctions
-nShow line numbers with output
-vInvert match, show lines NOT matching pattern
-rRecursively search directories
-cCount matching lines only

Key Takeaways

Use grep 'pattern' filename to find text in files.
Quote your pattern to avoid shell issues.
Use -i to search case-insensitively.
Add -n to see line numbers of matches.
Remember grep can search recursively with -r.