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

Strings के साथ grep

grep एक highlighter जैसा है जो text scan करता है उस word के लिए जिसकी आपको care है। एक string के साथ उपयोग होने पर, यह check करने में मदद करता है कि एक छोटा word एक बड़े word के अंदर छुपा है या नहीं।

In this page:

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

grep with Strings

grep text को एक pattern से match करने वाली lines के लिए search करता है और आमतौर पर echo या एक variable के साथ combine किया जाता है यह test करने के लिए कि क्या एक string में एक substring है।

grep -q output suppress करता है और सिर्फ exit status set करता है, जो एक if के अंदर handy है। grep -i match को case-insensitive बनाता है।

Note: यह test करने के लिए कि क्या एक variable में एक substring है, if echo "$text" | grep -q "pattern"; then उपयोग करें।

उदाहरण: 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. #}
आम गलतियां
  1. Pattern के आस-पास quotes भूल जाना, इसलिए shell इसे expand कर देता है।
  2. एक if में grep उपयोग करना -q के बिना, इसलिए matches screen पर print होते हैं।
  3. यह उम्मीद करना कि grep whole words match करे, जब यह substrings match करता है जब तक आप -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.