Hands on grep practical examples

08 Oct 2023

grep is a powerful command-line utility for searching text using regular expressions. Here are few practical grep command examples for various scenarios:

Search for a String in a File

   grep "search_term" filename
   grep -i "search_term" filename

Count the Number of Matches

   grep -c "search_term" filename

Search Recursively in a Directory

   grep -r "search_term" directory/

Search for Whole Words Only

   grep -w "word" filename

Search for Inverted Matches (Lines Not Containing)

   grep -v "search_term" filename

Display Line Numbers with Matches

   grep -n "search_term" filename

Search for Multiple Patterns (OR Logic)

   grep -e "pattern1" -e "pattern2" filename

Search for a Pattern in gzip File

   zgrep "search_term" filename.gz

Search for Lines Matching a Regular Expression

    grep -E "regex_pattern" filename

These examples cover a range of grep functionalities, from basic string searches to more advanced usage like regular expressions, case-insensitive searching, and searching in compressed files. You can adapt these commands to suit your specific needs when working with text data on the command line.