In this post, we will see about grep command in unix.
The grep command stands for “Global Regular Expression Print” and is used to search text or searches the given file for lines containing a match to the given strings or words. It is a powerful file pattern searcher in Linux and Unix-like operating systems. Let’s see how it can be used.
To install grep on Debain based distributions, use following command
For Redhat, CentOS and Fedora distributions
Working with Grep
If you want to search user arpit in /var.logs.application.log file, use the following command.
Output will be all lines in application.log file matching the string arpit. On my system output of above command is
$grep arpit /var/logs/application.log
Output of grep will be blank in case nothing match the search string.
Grep command is case sensitive. If you want to work without case sensitivity, use -i option
this will display all lines that match arpit, ARPIT, Arpit and all other combinations.
You can also search string in multiple files.
the above command will search arpit in application.log applicationBackup1.logapplicationBackup2.log files.
If you want to search every file in your current directory with a string.
this will search every file in current directory with string arpit.
To get name of all files having a specific string.
If string contains spaces, enclose it in double quotes
To highlight the successful matches, use the —color option
If you want to get line numbers where string is found
$ grep -n arpit application.log
Grep command allows you to search in subdirectories using -r option. -r tells grep to perform its search recursively.
this will read all files under each directory for a string arpit.
By default, grep displays the entire line having the matched string. If you want to display only the matched string, use -o option
Working with Grep
Using Grep with other commands
You can also use grep command in combination with other command by using pipeline ( | ) symbol. This option is very handy.
grep will read all files residing in /usr/bin directory and will display files whose filename contains string zip.
this will print all the file names that don’t have string zip. This is just like applying not operator to grep command.
above command will give the number of files having string zip.
this will give no of files that don’t have string zip.
This tutorial shows few cases of how grep command can be used, there are many more also. To learn more on grep please type $ man grep on your unix terminal.
That’s all about Grep command in unix.
Join Our News Letter – Stay Updated
Subscribe to Awesome Java Content.