15 grep Command Examples in Linux

«
»

This tutorial explains Linux “grep” command, options and its usage with examples.

grep – global regular expression parser – print lines matching a pattern

Description :

Grep searches the named input FILEs (or standard input if no files are named, or the file name – is given) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.

In addition, two variant programs egrep and fgrep are available. Egrep is the same as grep -E. Fgrep is the same as grep -F.

Usage :

grep [options] PATTERN [FILE…] grep [options] [-e PATTERN | -f FILE] [FILE…]

advertisement
advertisement

Options :

-e PATTERN, –regexp=PATTERN
Use PATTERN as the pattern to match. This can be used to specify multiple search patterns, or to protect a pattern beginning with a dash (-).
-f FILE, –file=FILE
Obtain patterns from FILE, one per line.
-i, –ignore-case
Ignore case distinctions in both the PATTERN and the input files.
-v, –invert-match
Invert the sense of matching, to select non-matching lines.
-w, –word-regexp
Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Or, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and underscores.
-x, –line-regexp
Select only matches that exactly match the whole line.
-y
The same as -i.
-E, –extended-regexp
Interpret PATTERN as an extended regular expression.
-F, –fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.
-G, –basic-regexp
Interpret PATTERN as a basic regular expression. This is the default option when running grep.
-P, –perl-regexp
Interpret PATTERN as a Perl regular expression. This functionality is still experimental, and may produce warning messages.
-c, –count
Instead of the normal output, print a count of matching lines for each input file. With the -v, –invert-match option (see below), count non-matching lines.
–color[=WHEN], –colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. The older environment variable GREP_COLOR is still supported, but its setting does not have priority. WHEN is never, always, or auto.
-L, –files-without-match
Instead of the normal output, print the name of each input file from which no output would normally have been printed. The scanning will stop on the first match.
-l, –files-with-matches
Instead of the normal output, print the name of each input file from which output would normally have been printed. The scanning will stop on the first match.
-m NUM, –max-count=NUM Stop reading a file after NUM matching lines. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or –count option is also used, grep does not output a count greater than NUM. When the -v or –invert-match option is also used, grep stops after outputting NUM non-matching lines.
-o, –only-matching
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
-q, –quiet, –silent
Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or –no-messages option.
-s, –no-messages
Suppress error messages about nonexistent or unreadable files.
-b, –byte-offset
Print the 0-based byte offset within the input file before each line of output. If -o (–only-matching) is specified, print the offset of the matching part itself.
-H, –with-filename
Print the file name for each match. This is the default when there is more than one file to search.
-h, –no-filename
Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.
–label=LABEL
Display input actually coming from standard input as input coming from file LABEL. This is especially useful when implementing tools like zgrep, e.g., gzip -cd foo.gz | grep –label=foo -H something. See also the -H option.
-n, –line-number
Prefix each line of output with the 1-based line number within its input file.
-T, –initial-tab
Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H, -n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width.
-u, –unix-byte-offsets
Report Unix-style byte offsets. This switch causes grep to report byte offsets as if the file were a Unix-style text file, i.e., with CR characters stripped off. This will produce results identical to running grep on a Unix machine. This option has no effect unless -b option is also used; it has no effect on platforms other than MS-DOS and MS-Windows.
-Z, –null
Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters.
-A NUM, –after-context=NUM
Print NUM lines of trailing context after matching lines. Places a line containing a group separator (–) between contiguous groups of matches. With the -o or –only-matching option, this has no effect and a warning is given.
-B NUM, –before-context=NUM
Print NUM lines of leading context before matching lines. Places a line containing a group separator (–) between contiguous groups of matches. With the -o or –only-matching option, this has no effect and a warning is given.
-C NUM, -NUM, –context=NUM
Print NUM lines of output context. Places a line containing a group separator (–) between contiguous groups of matches. With the -o or –only-matching option, this has no effect and a warning is given.
-a, –text
Process a binary file as if it were text; this is equivalent to the –binary-files=text option.
–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. By default, TYPE is binary, and grep normally outputs either a one-line message saying that a binary file matches, or no message if there is no match. If TYPE is without-match, grep assumes that a binary file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. Warning: grep –binary-files=text might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands.
-D ACTION, –devices=ACTION
If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped.
-d ACTION, –directories=ACTION
If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option.
–exclude=GLOB
Skip files whose base name matches GLOB (using wildcard matching). A file-name glob can use *, ?, and […] as wildcards, and \ to quote a wildcard or backslash character literally.
–exclude-from=FILE
Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under –exclude).
–exclude-dir=DIR
Exclude directories matching the pattern DIR from recursive searches.
-I
Process a binary file as if it did not contain matching data; this is equivalent to the –binary-files=without-match option.
–include=GLOB
Search only files whose base name matches GLOB (using wildcard matching as described under –exclude).
-r, –recursive
Read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -d recurse option.
-R, –dereference-recursive
Read all files under each directory, recursively. Follow all symbolic links, unlike -r.

Examples :

Consider a file name demo_file for examples.

$ cat demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.
 
Two lines above this line is empty.
And this is the last line.

1. Search for the given string in a single file

$ grep "this" demo_file
this line is the 1st lower case line in this file.
Two lines above this line is empty.
And this is the last line.

2. Checking for the given string in multiple files.

The grep output will also include the file name in front of the line that matched the specific pattern as shown below.

advertisement
$ cp demo_file demo_file1
 
$ grep "this" demo_*
demo_file:this line is the 1st lower case line in this file.
demo_file:Two lines above this line is empty.
demo_file:And this is the last line.
demo_file1:this line is the 1st lower case line in this file.
demo_file1:Two lines above this line is empty.
demo_file1:And this is the last line.

3. Case insensitive search

$ grep -i "the" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.
And this is the last line.

4. Match regular expression in files

$ grep "lines.*empty" demo_file
Two lines above this line is empty.

Note : A regular expression may be followed by one of several repetition operators:

advertisement

? The preceding item is optional and matched at most once.
* The preceding item will be matched zero or more times.
+ The preceding item will be matched one or more times.
{n} The preceding item is matched exactly n times.
{n,} The preceding item is matched n or more times.
{,m} The preceding item is matched at most m times.
{n,m} The preceding item is matched at least n times, but not more than m times.

5. Checking for full words, not for sub-strings

If you want to search for a word, and to avoid it to match the substrings use -w option. Just doing out a normal search will show out all the lines.

$ grep -i "is" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.
Two lines above this line is empty.
And this is the last line.

Please note that this output does not contain the line “This Line Has All Its First Character Of The Word With Upper Case”, even though “is” is there in the “This”, as the following is looking only for the word “is” and not for “this”.

$ grep -iw "is" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
Two lines above this line is empty.
And this is the last line.

6. Displaying lines before/after/around the match using grep -A, -B and -C

Here we will use piping with ifconfig command and grep.

$ ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0c:29:5f:d3:05  
          inet addr:192.168.10.144  Bcast:192.168.10.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe5f:d305/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:13191 errors:0 dropped:0 overruns:0 frame:0
          TX packets:11668 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:15336080 (15.3 MB)  TX bytes:1202354 (1.2 MB)
 
lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:5052 errors:0 dropped:0 overruns:0 frame:0
          TX packets:5052 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:531255 (531.2 KB)  TX bytes:531255 (531.2 KB)
 
$ ifconfig | grep -A 4 eth0
eth0      Link encap:Ethernet  HWaddr 00:0c:29:5f:d3:05  
          inet addr:192.168.10.144  Bcast:192.168.10.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe5f:d305/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:13185 errors:0 dropped:0 overruns:0 frame:0
 
$ ifconfig | grep -B 2 UP
          inet addr:192.168.10.144  Bcast:192.168.10.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe5f:d305/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
--
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
 
$ ifconfig | grep -C 2 UP
          inet addr:192.168.10.144  Bcast:192.168.10.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe5f:d305/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:13215 errors:0 dropped:0 overruns:0 frame:0
          TX packets:11680 errors:0 dropped:0 overruns:0 carrier:0
--
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:5072 errors:0 dropped:0 overruns:0 frame:0
          TX packets:5072 errors:0 dropped:0 overruns:0 carrier:0

7. Searching in all files recursively using grep -r

When you want to search in all the files under the current directory and its sub directory. -r option is the one which you need to use. The following example will look for the string “abcd” in all the files in the current directory and all it’s subdirectory.

$ grep -r "abcd" *

8. Invert match using grep -v

When you want to display the lines which does not matches the given string/pattern, use the option -v as shown below. This example will display all the lines that did not match the string 0 in output of ifconfig.

$ ifconfig | grep -v 0
 
lo        Link encap:Local Loopback  
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1

9. Display the lines which match all the given patterns

All the different patterns can be given using multiple -e options.

$ ifconfig | grep -e lo -e eth0
eth0      Link encap:Ethernet  HWaddr 00:0c:29:5f:d3:05  
lo        Link encap:Local Loopback

10. Display the lines which do not match all the given patterns

All the different patterns can be given using multiple -e options.

$ ifconfig | grep -v -e lo -e eth0
          inet addr:192.168.10.146  Bcast:192.168.10.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe5f:d305/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:16250 errors:0 dropped:0 overruns:0 frame:0
          TX packets:12815 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:15654297 (15.6 MB)  TX bytes:1303663 (1.3 MB)
 
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:6678 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6678 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:665985 (665.9 KB)  TX bytes:665985 (665.9 KB)

11. Counting the number of matches

When you want to count that how many lines matches the given pattern/string, then use the option -c.

$ ifconfig | grep -c inet
4

When you want do find out how many lines that does not match the pattern/string.

$ ifconfig | grep -vc inet
14

12. Display only the file names which matches the given pattern

When you give multiple files to the grep as input, it displays the names of file which contains the text that matches the pattern, will be very handy when you try to find some notes in your whole directory structure.

$ grep -l this demo_*
demo_file
demo_file1

13. Show only the matched string

By default grep will show the line which matches the given pattern/string, but if you want the grep to show out only the matched string of the pattern then use the -o option.

$ ifconfig | grep -o "inet.*"
inet addr:192.168.10.146  Bcast:192.168.10.255  Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe5f:d305/64 Scope:Link
inet addr:127.0.0.1  Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host

14. Show the position of match in the line

$ ifconfig | grep -b "addr"
0:eth0      Link encap:Ethernet  HWaddr 00:0c:29:5f:d3:05  
58:          inet addr:192.168.10.146  Bcast:192.168.10.255  Mask:255.255.255.0
135:          inet6 addr: fe80::20c:29ff:fe5f:d305/64 Scope:Link
533:          inet addr:127.0.0.1  Mask:255.0.0.0
579:          inet6 addr: ::1/128 Scope:Host

Note: The output of the grep command above is not the position in the line, it is byte offset of the whole file.

15. Show line number while displaying the output using grep -n

$ ifconfig | grep -n "addr"
1:eth0      Link encap:Ethernet  HWaddr 00:0c:29:5f:d3:05  
2:          inet addr:192.168.10.146  Bcast:192.168.10.255  Mask:255.255.255.0
3:          inet6 addr: fe80::20c:29ff:fe5f:d305/64 Scope:Link
11:          inet addr:127.0.0.1  Mask:255.0.0.0
12:          inet6 addr: ::1/128 Scope:Host

Note: It does 1-based line numbering for each file.

Sanfoundry Global Education & Learning Series – 1000 Linux Tutorials.

If you wish to look at all Linux commands and their usage examples, go to Linux Commands Tutorial.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.