# Linux commands: grep

> Learn how the Linux grep command matches patterns in files or piped output, with -n for line numbers, -C for context, -i to ignore case, and -v to invert.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2020-09-30 | Topics: [CLI](https://flaviocopes.com/tags/cli/) | Canonical: https://flaviocopes.com/linux-command-grep/

The `grep` command is a very useful tool, that when you master will help you tremendously in your day to day.

> If you're wondering, `grep` stands for _global regular expression print_

You can use `grep` to search in files, or combine it with pipes to filter the output of another command.

For example here's how we can find the occurences of the `document.getElementById` line in the `index.md` file:

```bash
grep -n document.getElementById index.md
```

![Terminal showing grep command output matching document.getElementById in index.md without line numbers](https://flaviocopes.com/images/linux-command-grep/Screen_Shot_2020-09-04_at_09.42.10.png)

Using the `-n` option it will show the line numbers:

```bash
grep -n document.getElementById index.md
```

![Terminal showing grep -n command output with line numbers 60 and 128 for document.getElementById matches](https://flaviocopes.com/images/linux-command-grep/Screen_Shot_2020-09-04_at_09.42.04.png)

One very useful thing is to tell grep to print 2 lines before, and 2 lines after the matched line, to give us more context. That's done using the `-C` option, which accepts a number of lines:

```bash
grep -nC 2 document.getElementById index.md
```

![Terminal showing grep -nC 2 output displaying matched lines with 2 lines of context before and after](https://flaviocopes.com/images/linux-command-grep/Screen_Shot_2020-09-04_at_09.44.35.png)

Search is case sensitive by default. Use the `-i` flag to make it insensitive.

As mentioned, you can use grep to filter the output of another command. We can replicate the same functionality as above using:

```bash
less index.md | grep -n document.getElementById
```

![Terminal showing piped grep command using less index.md with line numbers for document.getElementById matches](https://flaviocopes.com/images/linux-command-grep/Screen_Shot_2020-09-04_at_09.43.15.png)

The search string can be a regular expression, and this makes `grep` very powerful.

Another thing you might find very useful is to invert the result, excluding the lines that match a particular string, using the `-v` option:

![Terminal showing ls -al command and grep -v excluding lines that match index.md from the output](https://flaviocopes.com/images/linux-command-grep/Screen_Shot_2020-09-04_at_09.47.04.png)

> The `grep` command works on Linux, macOS, WSL, and anywhere you have a UNIX environment
