2025-3-22 Linux Literacy Grep

Here is the source Grep

setup a dir with a file named "file" with this content

1 This is a file
2
3
4 This is text
5
6
7
8
9

Inputs

There is 3 main way to feed inputs in grep:

File

grep text file

Gives the line 4

Dir (recursive)

grep -r text ./

Gives the line 4

Pipe

cat file | grep text

Gives the line 4

Options

Case insensitive

grep -i this file

line 1 and 4 event if not capitalized

grep -v text file

every line but 4

grep -w tex file

nothing

grep -w text file

works

grep -x 1 file

nothing

grep -x "1 This is a file" file

works

grep -e file -e text file

gives line 1 and 4

Display line number

grep -n text file

display line number in front of our actual line

Display line After/Before/(C)Both

grep -A1 text file

1 line after

grep -B2 text file

2 line before

grep -C3 text file

3 line before/after

Max number of line

grep -m1 This file

only the first "This"

Count

grep -c This file

will give 2 because 2 "This in file"

REGular EXpressions

grep -E t$ file

only 4 because end in "t"

Force color

useful when you pass grep to something else before printing.

grep --color=always useful info

Only color

did a mistake but ok (test)

Will print everything but color your search pattern.

grep "text\|$" file

The search text "search\|$" is actually a trick, it will match lines that have pattern OR lines that have an end. Because all lines have an end, all lines are matched, but the end of a line isn't actually any characters, so it won't be colored.[1]