grep की Basics
In this page:
grep [-i] [-v] [-c] [-r] "pattern" file_name
Basic Pattern Matching
grep pattern file file की हर line print करता है जिसमें pattern हो। बिना किसी file argument के, grep stdin से पढ़ता है, इसे pipelines के लिए एक natural fit बनाते हुए।
उदाहरण: Basic Pattern Matching
#!/bin/bash
printf "apple\nbanana\ncherry\napricot\n" > fruits.txt
grep "ap" fruits.txt
rm -f fruits.txt
Login to try C/C++/Java/PHP code in the editor
Case-Insensitive और Inverted Matches
-i match को case-insensitive बनाता है। -v logic को पूरी तरह flip करता है और सिर्फ वे lines print करता है जो pattern से match NOT करती।
उदाहरण: Case-Insensitive and Inverted Matches
#!/bin/bash
printf "Apple\nbanana\nAPRICOT\n" > fruits.txt
echo "case-insensitive:"
grep -i "apple" fruits.txt
echo "inverted:"
grep -v "banana" fruits.txt
rm -f fruits.txt
Login to try C/C++/Java/PHP code in the editor
Counting और Recursive Search
-c lines के बजाय matching lines की एक count print करता है। -r (या -R) एक directory tree में हर file को recursively search करता है, जो codebase के across usages ढूंढने के लिए handy है।
उदाहरण: Counting and Recursive Search
#!/bin/bash
mkdir -p code_demo
echo "TODO: fix this" > code_demo/a.txt
echo "nothing here" > code_demo/b.txt
echo "another TODO" > code_demo/c.txt
grep -c "TODO" code_demo/a.txt
grep -r "TODO" code_demo
rm -rf code_demo
Login to try C/C++/Java/PHP code in the editor
grep का Exit Status उपयोग करना
grep अगर कम से कम एक match मिला तो 0 exit होता है और अगर कोई नहीं मिला तो 1, जो scripts को matched text की care किए बिना यह branch करने देता है कि एक pattern मौजूद है या नहीं।
-q उपयोग करें जब आपको सिर्फ exit status की care हो, क्योंकि यह normal output पूरी तरह suppress करता है।उदाहरण: Using grep's Exit Status
#!/bin/bash
echo "hello world" > greeting.txt
if grep -q "hello" greeting.txt; then
echo "pattern found"
fi
if ! grep -q "goodbye" greeting.txt; then
echo "pattern not found, as expected"
fi
rm -f greeting.txt
Login to try C/C++/Java/PHP code in the editor
- यह भूल जाना कि
grepdefault रूप से case-sensitive है; case-insensitive matching के लिए-iचाहिए। grep pattern *उपयोग करना और हर line पर prefixed filenames से surprised होना; यह automatically होता है जब भी एक से ज़्यादा file search की जाए।- यह realize न करना कि grep का exit status (0 = मिला, 1 = नहीं मिला, 2 = error) खुद scripting के लिए useful है, सिर्फ इसका printed output नहीं।
grep -icase ignore करता है;-vmatch invert करता है (non-matching lines print करता है);-cmatching lines को print करने के बजाय count करता है।grep -rएक directory tree के through recursively search करता है।- grep का exit status 0 है अगर कम से कम एक match मिला, 1 अगर कोई नहीं मिला, और 2 एक error पर।
grep -nहर match को इसकी line number से prefix करता है, एक बड़ी file में matches locate करने के लिए useful।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: