Linux Grep Command
The grep command in Linux is used to search for a specific pattern of text in files or input. Below is a list of commonly used options with their descriptions:
| Option | Description |
|---|---|
-i |
Ignore case distinctions in patterns and data. |
-v |
Invert the match to select non-matching lines. |
-r or -R |
Recursively search directories for the pattern. |
-n |
Display line numbers with the matching lines. |
-c |
Count the number of matching lines. |
-l |
List only the names of files with matching lines. |
-w |
Match whole words only. |
-e |
Specify multiple patterns to search for. |
--color |
Highlight the matching text in the output. |
-A [num] |
Show [num] lines of trailing context after matching lines. |
-B [num] |
Show [num] lines of leading context before matching lines. |
-C [num] |
Show [num] lines of context around matching lines. |
-E |
Interpret the pattern as an extended regular expression. |
^ |
Match the beginning of a line. |
$ |
Match the end of a line. |
^[#] |
Match lines starting with a specific character (e.g., #). |
Example usage:
grep -i "pattern" filename :- This command searches for "pattern" in the specified file, ignoring case.
Grep Command with Pipe symbole
cat file.txt | grep -i "pattern"
Grep Command search with multiple words
grep -E "pattern1|pattern2" filename
Grep Command provide output with after some lines and before some lines or command some lines
Example:
grep -n -A 2 "pattern" filename
grep -n -B 2 "pattern" filename
grep -n -c 2 "pattern" filename