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

grep with Strings

grep is like a highlighter that scans text for a word you care about. Used with a string, it helps you check whether a smaller word is hiding inside a bigger one.

In this page:

  1. grep with Strings
Syntax
bash
echo "$variable" | grep [-q] "pattern"

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]*"
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 expands it.
  2. Using grep in an if without -q, so matches are printed to the screen.
  3. Expecting grep to match whole words, when it matches substrings unless you use -w.

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.