How to use Grep Command

 

The grep command is one of the most useful tools in Linux/Unix for searching text. It scans files or streams line by line and prints the lines that match a given pattern.

🔑 Basic Syntax

grep [options] pattern [file...]
  • pattern → the text or regex you want to search for
  • file → the file(s) you want to search in

📘 Common Examples

  • Search for a word in a file

    grep "error" logfile.txt
    

    → Shows all lines in logfile.txt containing the word error.

  • Case-insensitive search

    grep -i "error" logfile.txt
    

    → Matches Error, ERROR, error, etc.

  • Search recursively in a directory

    grep -r "TODO" ./src
    

    → Finds all lines with TODO in files under ./src.

  • Show line numbers

    grep -n "main" program.c
    

    → Displays matching lines with their line numbers.

  • Count matches

    grep -c "error" logfile.txt
    

    → Prints how many lines contain error.

  • Use regex patterns

    grep "^[0-9]" data.txt
    

    → Matches lines starting with a digit.

⚡ Useful Options

OptionMeaning
-iIgnore case
-nShow line numbers
-rRecursive search in directories
-vInvert match (show lines not matching)
-cCount matches
-EUse extended regex (like egrep)


Comments

Popular posts from this blog

How to build MCP Server and use MCP Inspector in Node

How to install ngrok in wsl for activepieces