The grep
command in Linux is a powerful tool used to search for specific patterns of text within files. It uses regular expressions to match lines that contain the specified pattern. This command is commonly used for filtering output or searching through logs and configuration files for specific entries.
Basic Syntax
grep [OPTIONS] PATTERN [FILEā¦]
. PATTERN
: The string or regular expression you want to search for
. FILE
: The file or files you want to search through. If no file is specified, grep
searches the standard input
Key Features and Examples
1. Basic Search
To search for a specific word or pattern within a file:

This command searches for the word “This” in the file data1.txt
and displays all lines that contain the word.
2. Case-Insensitive Search
The -i
option allows for a case-insensitive search, meaning it will match “This”, “THIS”, “this”, etc.

This command searches for “this” regardless of case in data1.txt
.
3. Display Line Numbers
The -n
option displays the line number along with the matched line, which is useful when you need to know where in the file the pattern occurs.

This command shows the line numbers of each line that contains “This” in data1.txt
.
List of common switches (options) for the grep command, along with brief explanations:
-C num: Print num lines of context (both before and after)
-i: Ignore case distinctions
-v: Invert the match (select non-matching lines)
-r or -R: Recursive search in directories
-l: Only print filenames of matching files
-n: Print line numbers along with matching lines
-w: Match whole words only
-c: Print only a count of matching lines
-A num: Print num lines of trailing context after matching lines
-B num: Print num lines of leading context before matching lines