grep

>Usage

grep (Global Regular Expression Print) is a powerful command-line tool that searches for specified patterns in files or text streams. It’s like having a digital magnifying glass that can find any text pattern you're looking for across one or multiple files.

>Synopsis

grep [options] pattern [files]

>Options

-i

-i (ignore case): Ignores case while searching for the pattern.

Example 1:

Dots

-zsh

> echo "Hello World" | grep -i "hello"


Hello World


!!! Grep normally reqires a file for input, but beacuse is allowed and for ease of explanations is used echo !!!

-r

-r (recursive): Searches files in directories and subdirectories.

Example 2:

Dots

-zsh

> grep -r "pattern" ./directory/


./directory/file.txt: pattern

-v

-v (invert match): Displays all lines that do not match the pattern.

Example 3:

Dots

-zsh

> echo -e "apple\nbanana\ncherry" | grep -v "banana"


apple
cherry

-l

-l (files with matches): Shows only the names of files that contain the pattern.

Example 4:

Dots

-zsh

> grep -l "error" *.log


error_log.txt

-n

-n (line number): Displays the line number along with the matching lines.

Example 5:

Dots

-zsh

> echo -e "line 1\nline 2\nline 3" | grep -n "line 2"


2:line 2

-w

-w (word match): Matches the exact word, not just a substring.

Example 6:

Dots

-zsh

> echo -e "apple pie\npineapple" | grep -w "apple"


apple pie

-c

-c (count matches): Counts the number of lines that match the pattern.

Example 7:

Dots

-zsh

> echo -e "apple\nbanana\napple" | grep -c "apple"


2

-o

-o (only matching): Outputs only the matched parts of the line.

Example 8:

Dots

-zsh

> echo "apple banana apple" | grep -o "apple"


apple
apple

-A

-A (after context): Shows a specified number of lines after the matching line.

Example 9:

Dots

-zsh

> echo -e "apple\nbanana\ncherry" | grep -A 1 "banana"


banana
cherry

-B

-B (before context): Shows a specified number of lines before the matching line.

Example 10:

Dots

-zsh

> echo -e "apple\nbanana\ncherry" | grep -B 1 "banana"


apple
banana

>Quiz

Progress: Question ? out of ?

Question Title

Page written by Andrea Benvegnù