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

grep

In this page:

  1. grep

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

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.