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:
Syntax
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
#!/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 try C/C++/Java/PHP code in the editor
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
- Forgetting quotes around the pattern, so the shell expands it.
- Using
grepin anifwithout-q, so matches are printed to the screen. - Expecting
grepto match whole words, when it matches substrings unless you use-w.
🔒
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: