1. Simple Text Search (grep string)
The grep command is used to search for patterns within text files. By default, it searches for exact matches of the given string and outputs the lines that contain it.
Basic Syntax:
grep 'string' filenameThis will search for occurrences of the string string in the filename and display all lines containing that string.
Example:
To search for the word apple in fruit.txt:
grep 'apple' fruit.txtExample Output:
I love apple pie.
The apple is delicious.
grep will display all the lines where apple appears.
2. Case-Insensitive Text Search (grep -i string)
By default, grep is case-sensitive, meaning it only matches the exact case of the string. If you want to perform a case-insensitive search (i.e., search for apple, Apple, APPLE, etc.), use the -i option.
Syntax:
grep -i 'string' filenameExample:
To search for apple in a case-insensitive manner in fruit.txt:
grep -i 'apple' fruit.txtExample Output:
I love apple pie.
The Apple is delicious.
APPLE is my favorite fruit.
This will match any variation of apple, regardless of the case.
3. Search for Text at the Beginning of Each Line (grep ^string)
You can search for a string only at the beginning of each line by using the caret symbol (^). The caret symbol represents the beginning of a line.
Syntax:
grep '^string' filenameExample:
To search for lines that start with apple in fruit.txt:
grep '^apple' fruit.txtExample Output:
apple pie is delicious.
apple is my favorite fruit.
This will show only the lines where the word apple appears at the beginning of the line.
4. Search for Text at the End of Each Line (grep string$)
You can search for a string only at the end of each line by using the dollar sign ($). The dollar symbol represents the end of a line.
Syntax:
grep 'string$' filenameExample:
To search for lines that end with pie in fruit.txt:
grep 'pie$' fruit.txtExample Output:
apple pie is delicious.
banana pie is my favorite.
This will display only the lines where pie is at the end of the line.
Summary of grep Usage:
grep 'string' filename: Searches for an exact match ofstringinfilename.grep -i 'string' filename: Performs a case-insensitive search.grep '^string' filename: Searches for lines wherestringappears at the beginning of the line.grep 'string$' filename: Searches for lines wherestringappears at the end of the line.