Let's break down the `grep` command and its options.
**The `grep` command**
`grep` is a powerful Unix/Linux utility for searching for patterns within text files. It
stands for "global regular expression print," but don't worry about the technical
details; we'll get to that later.
**Recursive search with `-r`**
When you add the `-r` option (short for recursive) before the pattern, `grep` will search
all subdirectories recursively. This means it will look for the specified pattern in
files and directories within your current working directory, as well as their
subdirectories.
Here's an example:
bash
grep -rn "searchText" *
In this case, `grep` will start searching from your current working directory (`*`) and
traverse all subdirectories recursively to find lines containing the string
`"searchText"`.
**Displaying line numbers with `-n`**
The `-n` option tells `grep` to prefix each matching line with its corresponding line
number. This makes it easier to identify where in the file the match occurred.
When combined with the recursive search, you get:
bash
grep -rn "searchText" *
This will display lines containing `"searchText"` along with their respective line
numbers.
**How `grep` matches patterns**
Now, let's talk about how `grep` actually finds matching text. By default, it uses a
simple string matching algorithm. You can use various options to modify this behavior,
such as:
* `-E`: Use extended regular expressions (EREs) for more complex pattern matching.
* `-v`: Invert the search; display non-matching lines instead.
For example:
bash
grep -rn -v "searchText" *
This will show you all lines that **don't** contain `"searchText"` along with their line
numbers.
**Common options and usage**
Here are some additional `grep` options and examples to keep in mind:
* `-h`: Suppress the file name prefix for each match.
* `-q`: Quiet mode; don't display anything, just exit with a status code indicating
whether any matches were found.
* `-r` (again): Recursive search.
bash
# Search all files recursively, ignoring hidden ones:
grep -rn "searchText" .[^.]*
# Search the current directory and its immediate subdirectories only:
grep -n "searchText" .
# Use a regular expression pattern to find matches in a specific file:
grep -E "[0-9]{3}-[A-Z][a-z]+" example.txt
Remember, you can combine multiple options to achieve more complex searches. Experiment
with different combinations of options and patterns to get the most out of `grep`!