← Back to Bash Course | Chapter 5: Functions | Lesson 10 of 11

grep with Strings

In this page:

  1. grep with Strings

grep with Strings

grep searches text for lines matching a pattern and is commonly combined with echo or a variable to test whether a string contains a substring. grep -q suppresses output and just sets the exit status, which is handy inside an if. grep -i makes the match case-insensitive.

Note: Use if echo "$text" | grep -q "pattern"; then to test whether a variable contains a substring.

Example: grep with Strings

bash
#!/bin/bash
text="The quick brown fox"

if echo "$text" | grep -q "quick"; then
    echo "Found 'quick' in the text"
fi

echo "$text" | grep -o "[a-z]*o[a-z]*"

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.