🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Grep

Grep is a search command that finds lines matching a word. It prints the matching lines from a file.

Print matching lines

Grep prints each line that contains the word apple. Lines without the word stay hidden.

echo "apple" > fruits.txt
echo "banana" >> fruits.txt
echo "apple pie" >> fruits.txt
echo "cherry" >> fruits.txt
grep apple fruits.txt

Count matching lines

The -c option prints a count instead of the lines. Two lines contain the word apple.

echo "apple" > fruits.txt
echo "banana" >> fruits.txt
echo "apple pie" >> fruits.txt
echo "cherry" >> fruits.txt
grep -c apple fruits.txt

Print non-matching lines

The -v option flips the search around. It prints the lines without the word apple.

echo "apple" > fruits.txt
echo "banana" >> fruits.txt
echo "apple pie" >> fruits.txt
echo "cherry" >> fruits.txt
grep -v apple fruits.txt

Example

echo "Apple" > fruits.txt
echo "banana" >> fruits.txt
echo "apple" >> fruits.txt
cat fruits.txt | grep -i apple

Key points

  • Use grep with a word and a file to print matching lines.
  • The -c option prints a count of matching lines.
  • The -v option prints the lines that do not match.
  • The -i option ignores letter case while matching.
  • A pipe can send file contents into grep.

In this example, a pipe sends the file contents into grep. The -i option ignores letter case, so Apple and apple both match. The banana line does not match and stays hidden.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which grep option counts the matching lines?