# Searching inside files: grep

Course: Terminal Basics — https://zero2vibecode.com/learn/terminal-basics
Canonical URL: https://zero2vibecode.com/learn/terminal-basics/3-2-searching-text-with-grep

`grep` prints the lines of a file that contain the text you are looking for. It turns a thousand-line log into the four lines that matter.

`find` locates files by name. `grep` looks *inside* them.

## grep pattern file

```
grep ERROR server.log
```

```
ERROR database timeout
ERROR disk full
```

The file had six lines. Two of them contained `ERROR`, so those two came back — in full, exactly as they appear in the file.

That is grep's entire model: go through the file line by line, keep the lines that contain the pattern, print them.

The name comes from an old text-editor command, `g/re/p`. Nobody remembers that, and the word has long since become a verb — people say "grep the logs" the way they say "google it".

## The four flags worth knowing

| Flag | Effect |
|---|---|
| `-i` | ignore case, so `ERROR` and `error` both match |
| `-n` | show the line number of each match |
| `-c` | print only how many lines matched |
| `-v` | invert it: show the lines that do **not** match |

`-v` is the underrated one. When a log is 95 percent routine noise, filtering the noise out is often faster than describing the signal:

```
grep -v INFO server.log
```

## Silence means zero matches

```
grep TODO notes.txt
```

If nothing comes back, nothing matched. That is a real answer, not a failure — and it is different from an error, which would print something like `No such file or directory`.

When a search comes back empty and you expected results, try `-i` first. Roughly half the time the text is there and the capitalisation is not what you assumed.

## Try it

The log has six lines: four routine, two problems.

1. `cat server.log` — read the whole thing, so you can see what grep is filtering.
2. `grep ERROR server.log` — the two lines that matter.
3. `grep -i error server.log` — the same result, but now it would also catch `Error` or `error`.

Then experiment: `grep -v INFO server.log`, `grep -n ERROR server.log`, `grep -c INFO server.log`. Six lines is small enough to check every answer by eye, which is the best way to build trust in a filter.
