← Back to Bash Course | Chapter 11: Process Management | Lesson 2 of 12

grep

grep is like a search-and-highlight tool that reads through lines of text and shows you only the ones that contain the word you are hunting for.

In this page:

  1. grep
Syntax
bash
grep [-i] [-n] [-v] "pattern" file_name

grep

grep searches input for lines matching a pattern and prints the matching lines. Common flags include -i (case-insensitive), -v (invert match), -n (show line numbers), and -r (recursive over a directory).

It's one of the most frequently used text-processing tools in shell scripting.

Note: grep -v pattern prints every line that does *not* match — useful for filtering out noise.

Example: grep

bash
#!/bin/bash
printf "apple\nbanana\ncherry\navocado\n" > fruits.txt

echo "Lines containing 'a':"
grep "a" fruits.txt

echo "Lines starting with 'a':"
grep "^a" fruits.txt
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting quotes around the pattern, so the shell interprets special characters.
  2. Using grep with regex characters like . and expecting a plain string; use -F.
  3. Checking grep results in an if without -q.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.