Table of Contents
In this article, I will take you through 31 Useful grep command examples in Linux/Unix. grep is an open source tool that can be used for searching text/word/strings from files and directories in Linux and Unix based Operating Systems. It is one of the best searching tool currently in use. This tool also provides us the capability to do search based on Regular Expressions which makes it further useful in analyzing logs and files for troubleshooting purposes. Another important use of grep command which you will often see is in Linux Scripting. Here, we will go through different examples of grep command to understand its usages.
Syntax
grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
grep command examples in Linux/Unix
Also Read: 10 Useful iproute2 tools examples to Manage Network Connections in Linux
Example 1: How to use grep command in Linux/Unix
Let's say we have an example file file1.txt
which has two lines and we want to search some word/string from this file.
[root@localhost ~]# cat file1.txt This is cyberithub Hello World
We will try to search a word cyberithub
from file1.txt
file using grep cyberithub file1.txt
command as shown below. You might be interested in 11 Best Linux route command examples (How to add route in Linux)
[root@localhost ~]# grep cyberithub file1.txt This is cyberithub
NOTE:
root
user to run all the below commands.You can use any user with sudo
access to run all these commands. For more information Please check Step by Step: How to Add User to Sudoers to provide sudo
access to User.Example 2: Ignore Case Distinction using grep command in Linux
Usually searching through grep command by default is case sensitive. But if you want to ignore the case sensitivity then you need to use -i
option with grep command as shown below. In this example we are using below file1.txt
.
[root@localhost ~]# cat file1.txt This is cyberithub This is CYBERITHUB Hello World
Now if you want to remove case sensitivity then you need to use -i
option with grep command as mentioned in the below output. You might want to check 26 Useful Firewall CMD Examples on RedHat/CentOS 7
[root@localhost ~]# grep -i cyberithub file1.txt This is cyberithub This is CYBERITHUB
-i : Ignore case distinctions in both the PATTERN and the input files.
Example 3: Check grep command version
If you want to check the grep command version then you need to use -V
option as shown below. As you can see from below output grep command version is 2.20
.
[root@localhost ~]# grep -V grep (GNU grep) 2.20 Copyright (C) 2014 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Written by Mike Haertel and others, see <http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>.
-V : Print the version number of grep to the standard output stream.
Example 4: Invert Search Pattern using grep command
If you want to invert a word matching then you need to use -v
option with grep command. In this example we are trying to search everything but cyberithub
word using grep -v cyberithub file1.txt
command as shown below.
[root@localhost ~]# grep -v cyberithub file1.txt This is CYBERITHUB Hello World
-v : Invert the sense of matching, to select non-matching lines.
If you also want to invert case sensitive cyberithub
word then you need to add -i
option in the above command to invert matching all case sensitive cyberithub
keyword.
[root@localhost ~]# grep -i -v cyberithub file1.txt Hello World
Example 5: Display N Lines after pattern match
If you want to display N Lines after the matched word/string line then you need to use -A
option with grep command as shown below. In this example we are trying to display next 3 Lines of the matched word PermitTunnel
Line.
[root@localhost ~]# grep -A 3 PermitTunnel /etc/ssh/sshd_config #PermitTunnel no #ChrootDirectory none #VersionAddendum none
-A : Print NUM lines of trailing context after matching lines.
If you want to use above command with case sensitivity option disabled then you need to use -i
option as shown below. You might want to check 10 Useful swapon command examples in Linux (RedHat/CentOS 7/8)
[root@localhost ~]# grep -A 3 -i permitTunnel /etc/ssh/sshd_config #PermitTunnel no #ChrootDirectory none #VersionAddendum none
Example 6: Display N Lines before pattern search
If you want to display N Lines before the matched word then you need to use -B
option with grep command as shown below. In this example, we are trying to display three lines of leading context before matching lines that contains PermitTunnel
word.
[root@localhost ~]# grep -B 3 PermitTunnel /etc/ssh/sshd_config #UseDNS yes #PidFile /var/run/sshd.pid #MaxStartups 10:30:100 #PermitTunnel no
-B : Print NUM lines of leading context before matching lines.
If you want to search a word with case sensitivity disabled then you can again use above command with -i
option as shown below. You might want to check 25+ Popular Examples of Openssl Commands in Linux (RedHat/CentOS 7/8)
[root@localhost ~]# grep -B 3 -i PERmitTunnel /etc/ssh/sshd_config #UseDNS yes #PidFile /var/run/sshd.pid #MaxStartups 10:30:100 #PermitTunnel no
Example 7: Display N Lines above and below the matched pattern
If you want to display n Lines above and below the matched word Line then you need to use -C
option with grep command as shown below. In this example we are trying to display 3 lines before and after the Line that contains matched PermitTunnel
word.
[root@localhost ~]# grep -C 3 PermitTunnel /etc/ssh/sshd_config #UseDNS yes #PidFile /var/run/sshd.pid #MaxStartups 10:30:100 #PermitTunnel no #ChrootDirectory none #VersionAddendum none
-C : Print NUM lines of output context.
Example 8: Perform Recursive Search Operations
If you want to perform recursive search operations then you need to use -r
option with grep command as shown below. In this example we are trying to search cyberithub
word in all the files and directories recursively in the current path. You might want to check 10 Popular examples of sudo command in Linux (RedHat/CentOS 7/8)
[root@localhost ~]# grep -r cyberithub * file1.txt:This is cyberithub file2.txt:This is from cyberithub file2.txt:Hello from cyberithub
-r : Read all files under each directory, recursively, following symbolic links only if they are on the command line.
Example 9: Display Lines with exact matches
If you want to display lines contains exact matches then you need to use -x
flag with grep command as shown below. Here we are trying to display line which contains exactly "This is cyberithub"
from file1.txt
file.
[root@localhost ~]# grep -x "This is cyberithub" file1.txt This is cyberithub
-x : Select only those matches that exactly match the whole line. More information on grep man page.
Example 10: Search a word/string in All the Files
If you want to search a specific word in all the files then you can use *
operator as shown below. In this example, we are trying to search cyberithub
word from all the files in current location.
[root@localhost ~]# grep cyberithub * file1.txt:This is cyberithub file2.txt:This is from cyberithub file2.txt:Hello from cyberithub
Example 11: Count number of matched words using grep command
If you want to count the number of matched keyword from every files in the current directory then you need to use below grep command. In this example we are counting the number of cyberithub
keyword from all the files in the current path. You might want to check How to disable or delete Logical Volume(LVM) in Linux Using 4 Easy Steps.
[root@localhost ~]# grep -c cyberithub * cyberithub.crt:0 cyberithub.csr:0 file1.txt:1 file2.txt:2 file.tar:0 file.zip:0 Network.class:0 Network.java:0 newserver.key:0 output.txt:0
-c : Suppress normal output; instead print a count of matching lines for each input file.
Example 12: Display output with exact matches
If you only want to display lines containing matches of whole word then you need to use -w
option as shown below. In this example we are trying to display only those lines of all the files in current path which contains cyberithub
word as a whole word.
[root@localhost ~]# grep -w cyberithub * file1.txt:This is cyberithub file2.txt:This is from cyberithub file2.txt:Hello from cyberithub
-w : Select only those lines containing matches that form whole words.
Example 13: Display Only Matched Pattern using grep command
If you want to display only the matched part instead of displaying the entire Line then you need to use -o
option with grep command as shown below. In this example we are trying to search cyberit
keyword from all the files present in the current path.
[root@localhost ~]# grep -o cyberit * file1.txt:cyberit file2.txt:cyberit file2.txt:cyberit
-o : Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
Example 14: Display Line number of searched word/string
If you want to display Line number of the matched word from the file along with the grep search output then you need to use -n
option as shown below. In this example, we are trying to search the Line number of matched word cyberit
from all the files in the current path.
[root@localhost ~]# grep -n cyberit * file1.txt:1:This is cyberithub file2.txt:1:This is from cyberithub file2.txt:2:Hello from cyberithub
-n : Prefix each line of output with the 1-based line number within its input file.
Example 15: Display Filename containing matched pattern
If you want to display file name instead of its matched pattern contents then you need to use -l
option as shown below. In this example we are trying to display all the file names which contains cyberit
keyword as shown below.
[root@localhost ~]# grep -l cyberit * file1.txt file2.txt
-l : Suppress normal output; instead print the name of each input file from which output would normally have been printed.
Example 16: Using Regular Expressions to search a word/string
If you want search some string or keyword at the beginning of a line then you need to use ^
operator as shown in below grep command. In this example we are trying to search all the Lines that contains this
word at the beginning of the line with case sensitive option disabled.
[root@localhost ~]# grep -i "^this" * file1.txt:This is cyberithub file1.txt:This is CYBERITHUB file2.txt:This is from cyberithub
Similarly, If you want to search some keyword at the end of the line then you need to use $
operator at the end of the keyword as shown in below grep command.
[root@localhost ~]# grep -i "cyberithub$" * file1.txt:This is cyberithub file1.txt:This is CYBERITHUB file2.txt:This is from cyberithub file2.txt:Hello from cyberithub
Example 17: Using Multiple Search Pattern
If you want to provide multiple different search pattern then you can use -e
option multiple times with every search pattern as shown below. In this example we are trying to search two words is and from using grep -e is -e from *
command as shown below.
[root@localhost ~]# grep -e is -e from * anaconda-ks.cfg:timezone America/New_York --isUtc file1.txt:This is cyberithub file1.txt:This is CYBERITHUB file2.txt:This is from cyberithub file2.txt:Hello from cyberithub
-e : This can be used to specify multiple search patterns, or to protect a pattern beginning with a hyphen (-).
Example 18: Search Specific Time Range Logs
If you want to search logs based on specific time range then you can use below regular expression with grep command. In this example we are trying to display all the logs between 17:22:52
and 17:22:54
from /var/log/messages
path.
[root@localhost ~]# grep 17:22:5[2-4] /var/log/messages May 19 17:22:52 localhost dhclient[1364]: DHCPREQUEST on enp0s3 to 255.255.255.255 port 67 (xid=0x682eb278) May 20 17:22:54 localhost dhclient[1364]: DHCPREQUEST on enp0s3 to 192.168.0.1 port 67 (xid=0x3c61d7df)
Example 19: Search Strings based on Regex
You can also search strings based on regular expression as shown below. Here we assumed that someone forgot the entire spelling of cyberithub
word and only remembers the first four cyber
and last three hub
letters. In that case he can provide a range of letters to the possible from all the files in current location.
[root@localhost ~]# grep cyber[e-j][r-t]hub * file1.txt:This is cyberithub file2.txt:This is from cyberithub file2.txt:Hello from cyberithub
Example 20: Using grep command with other Linux commands
You can also cascade grep command with other Linux commands as shown below. In this example we are looking for network interface enp0s3
from ifconfig -a
output. You might want to check How to List/Get/Display/Find MAC Address in Linux Using 11 Popular Methods.
[root@localhost ~]# ifconfig -a | grep -i enp0s3 enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
Example 21: Using color output with grep command
If you want to change the color setting in the grep search output then you need use --color
option as shown below. In this example we are trying to remove the color from grep search output by setting --color=never
.
[root@localhost ~]# grep -i cyberithub * --color=never file1.txt:This is cyberithub file1.txt:This is CYBERITHUB file2.txt:This is from cyberithub file2.txt:Hello from cyberithub
Example 22: Search Files which appears to be binary
If you want search through binary files as text files then you need to use --binary-files
option as shown below. In this example we are trying to treat all binary files as text files while running grep search for word cyberithub
using grep --binary-files=text -i cyberithub *
command as shown below.
[root@localhost ~]# grep --binary-files=text -i cyberithub * file1.txt:This is cyberithub file1.txt:This is CYBERITHUB file2.txt:This is from cyberithub file2.txt:Hello from cyberithub
--binary-files=TYPE : If the first few bytes of a file indicate that the file contains binary data, assume that the file is of type TYPE.
Example 23: Redirect grep command output to a file
If you want to redirect or save the output of grep command in a different file then you can easily do that by using redirection operator as shown below. In this example, we are trying to save the grep search output to testfile.txt
.
[root@localhost ~]# grep -i cyberithub file1.txt > testfile.txt [root@localhost ~]# cat testfile.txt This is cyberithub This is CYBERITHUB
Example 24: Include Symlinks in grep command search
If you want to include symlinks in grep search then you need to use -R
option as shown below. In this example we are trying to search keyword cyberithub
recursively from all the /root
files and directories.
[root@localhost ~]# grep -R cyberithub /root/ /root/file2.txt:This is from cyberithub /root/file2.txt:Hello from cyberithub
-R : Read all files under each directory, recursively. Follow all symbolic links
Example 25: Using grep command in Quiet Mode
If you do not want to show the grep search output then you need to use -q
option as shown below. This option is frequently used in Bash or Shell Scripting in Linux. The best way to check the quiet mode is by checking exit status. If grep search is successful then you will get 0
in exit status as explained in below example.
[root@localhost ~]# grep -q cyberithub * [root@localhost ~]# echo $? 0
-q : Quiet; do not write anything to standard output.
If you do not find the word or string from the file then exit status will show non-zero number as mentioned below. You might want to check 8 Popular chkconfig command examples on RedHat/CentOS 7
[root@localhost ~]# grep -q cybethub file1.txt [root@localhost ~]# echo $? 1
Example 26: Using Egrep option with grep command
If you want to use egrep option with grep command to include more operators in search pattern then you need to use -E
option as shown below. In this example we are trying to use +
operator in regex to search pattern from file1.txt
file but before that let's use +
operator without -E
option and check if the grep command displays the matched output.
[root@localhost ~]# grep "cyber(+i)thub" file1.txt [root@localhost ~]# grep -E "cyber(+i)thub" file1.txt This is cyberithub
-E : Use Egrep
Similarly, if you want to use ?
operator in regex to search some specific word then you need to use below grep command.
[root@localhost ~]# grep "cyber(?i)thub" file1.txt [root@localhost ~]# grep -E "cyber(?i)thub" file1.txt This is cyberithub
Example 27: Suppressing File Name Prefix in the output
If you want to suppress file name prefix from the grep search output then you need to use -h
option as shown in below given example. In this example we are trying to suppress file name prefix during grep search for word cyberithub
but before that let's run a simple search using grep command and check the output.
[root@localhost ~]# grep cyberithub * file:This is cyberithub file1.txt:This is cyberithub file2.txt:This is from cyberithub file2.txt:Hello from cyberithub
Now if you want to suppress all the file name prefix in grep search output of word cyberithub
from the current path then you need to use -h
option as shown below.
[root@localhost ~]# grep -h cyberithub * This is cyberithub This is cyberithub This is from cyberithub Hello from cyberithub
-h : Suppress the prefixing of file names on output.
Example 28: Stop Displaying output after a MAX Count
If you want to stop displaying the grep search output after a specific number of count then you need to specify the number of count using -m
option as shown below. In this example we are trying to limit the count of cyberithub
word to 1 but before that let's run simple grep search and check the total number of cyberithub word.
[root@localhost ~]# grep cyberithub file2.txt This is from cyberithub Hello from cyberithub
Now if you want to stop displaying the grep search output of word cyberithub
after the count of then you need to use grep -m 1 cyberithub file2.txt
command as shown below.
[root@localhost ~]# grep -m 1 cyberithub file2.txt This is from cyberithub
-m NUM : Stop reading a file after NUM matching lines.
Example 29: Exclude Some Files from grep search
If you want exclude some files from grep search then you need use --exclude
option as explained below. In this example we will try to exclude a file file2.txt
from grep search of all the files in current path. Before that let's run simple grep command and check the number of files in which this word exists.
[root@localhost ~]# grep cyberithub * file:This is cyberithub file1.txt:This is cyberithub file2.txt:This is from cyberithub file2.txt:Hello from cyberithub
Now if you want exclude some file from the grep command search then you need to use --exclude
option as shown below.
[root@localhost ~]# grep --exclude=file2.txt cyberithub * file:This is cyberithub file1.txt:This is cyberithub
--exclude : Skip files whose base name matches GLOB (using wildcard matching).
Example 30: Exclude Directory from grep command search
If you want to exclude some directory from grep search then you need to use --exclude-dir
option and pass the directory name as shown below. In this example we are trying to exclude testdir
from grep search pattern of word cyberithub
from all the files in current path.
[root@localhost ~]# grep -r --exclude-dir=testdir cyberithub * file2.txt:This is from cyberithub file2.txt:Hello from cyberithub
--exclude-dir : Exclude directories matching the pattern DIR from recursive searches.
Example 31: Check Other grep command options
If you want to check all the other options available with grep command then you need to use grep --help
command as shown below. You might want to check Install iperf and perform network throughput test in Linux (RedHat/Linux 7/8) in 5 Easy Steps.
[root@localhost ~]# grep --help Usage: grep [OPTION]... PATTERN [FILE]... Search for PATTERN in each FILE or standard input. PATTERN is, by default, a basic regular expression (BRE). Example: grep -i 'hello world' menu.h main.c Regexp selection and interpretation: -E, --extended-regexp PATTERN is an extended regular expression (ERE) -F, --fixed-strings PATTERN is a set of newline-separated fixed strings -G, --basic-regexp PATTERN is a basic regular expression (BRE) -P, --perl-regexp PATTERN is a Perl regular expression -e, --regexp=PATTERN use PATTERN for matching -f, --file=FILE obtain PATTERN from FILE -i, --ignore-case ignore case distinctions -w, --word-regexp force PATTERN to match only whole words -x, --line-regexp force PATTERN to match only whole lines -z, --null-data a data line ends in 0 byte, not newline Miscellaneous: -s, --no-messages suppress error messages -v, --invert-match select non-matching lines -V, --version display version information and exit --help display this help text and exit
Recommended Posts:-
Understanding Kafka Console Producer and Consumer in 10 Easy Steps
Popular firewalld examples to open a port on RedHat/CentOS 7
8 Most Popular mkdir command in Linux with Examples
26 Useful Firewall CMD Examples on RedHat/CentOS 7
12 Most Popular rm command in Linux with Examples
9 useful w command in Linux with Examples
Popular Apache Kafka Architecture Explained Using 4 Basic Components
5 Easy Steps to recover LVM2 Partition , PV , VG , LVM metadata in Linux