What is Grep Command?
The grep command allows you to search one file or multiple files for lines that contain a pattern.
If Grep is not installed in your system you can install by using the following command.
$ sudo apt-get install grep #Debian/Ubuntu
$ sudo yum install grep #RHEL/CentOS/Fedora
Syntax For Grep Commands
grep [options] pattern [files]
-b Display the block number at the beginning of each line.
-c Display the number of matched lines.
-h Display the matched lines, but do not display the filenames.
-i Ignore case sensitivity.
-l Display the filenames, but do not display the matched lines.
-n Display the matched lines and their line numbers.
-s Silent mode.
-v Display all lines that do NOT match.
-w Match whole word.
Here Some of the examples for using Grep
1)How to Search a Given word in a single File
grep "String_name" filename
2)How to Search a String in Multiple File
grep "string" FILE_PATTERN
The Above example will used to search the string in multiple files.For Example,We have 2 text files named as textfile1 and textfile2.
Now the following command will use to search the string in these two text files
grep "search_string" text*
3)How will do Case insensitive search
Using -i option you can do the case insensitive search.
grep -i "string" Filename
4)How search a string in recursively
Using -r option will do the recursive search.
grep -r "string" *
5)How to count the number of Matches
Using -c option you can count the number of matches.
grep -c "string" Filename