15+ grep command Examples in Linux

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

Grep Command:
The ‘grep‘ command stands for “global regular expression parser“. It is used to find lines in files that match a specific pattern. By default, ‘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, and it 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.

Syntax:

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

Options Description:

  • -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: Shows lines with whole word matches. It checks if the match is at the start or follows a non-word character, or if it’s at the end or preceded by a non-word character. Word-constituent characters include 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]: Adds color to matched text, lines, context, file names, line numbers, and more on the terminal. The color scheme is defined by GREP_COLORS. WHEN can be 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: Limits the search to NUM matching lines. Stops searching once this limit is reached. Helps manage search results and performance.
  • -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.
  • -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: Aligns text neatly on tabs, improving readability with options like -H, -n, and -b. Ensures consistent spacing for line numbers and byte offsets.
  • -u, –unix-byte-offsets: Reports byte positions Unix-style, suitable for Unix-like systems with -b option.
  • -Z, –null: Replaces the character after a filename with a zero byte (NUL), useful for clear output with unique filenames.
  • -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: Decides what to do with non-text files. Default is “Binary”, showing a message on non-text matches. “Without-match” ignores them. “Text” treats them as text but may display odd characters.
  • -D ACTION, –devices=ACTION: Deals with special files like devices or sockets. Default is “read”, treating them as regular files. Choose “skip” to ignore them quietly.
  • -d ACTION, –directories=ACTION: Controls how to handle directories. “Read” treats them as files (default), “skip” ignores them, and “recurse” reads all files under directories, like -r.
  • –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
  • –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: It process binary files as non-matching data.
  • –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.

Grep Command 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.

Example 1: Searching for a String in a Single File

advertisement
advertisement

This example demonstrates how the grep command is used to find and display lines containing the word ‘this’ within the ‘demo_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.

Example 2: Searching for a 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.

$ 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.

Example 3: Case-Insensitive Search

In this example, we’re using the grep command with the ‘-i‘ option to perform a case-insensitive search for the word ‘the‘ in the ‘demo_file’.

$ 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.

Example 4: Match Regular Expressions in Files

advertisement
$ 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:

  • ? 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.

Example 5: Checking for Full Words (Not Substrings)

To search for full words and avoid matching substrings, use the ‘-w’ option with grep. Here’s the difference:
Without ‘-w’:
This matches lines containing “is”, including substrings like “this”.

advertisement
$ 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.

With ‘-w’:

$ 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.

Please remember that the command’s result does not show the line ‘This Line Has All Its First Characters Uppercased’, even though ‘is’ is part of ‘This’. The ‘-w’ option specifically looks for the word ‘is’ by itself and doesn’t match it within other words like ‘this’.

Example 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)

Display Lines After a Match with “-A”

$ 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

Display Lines Before a Match with “-B”

$ 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

Display Lines Around a Match with “-C”

$ 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

Example 7: Searching in All Files Recursively Using grep -r

To search for a string (“abcd” in this case) in all files within the current directory and its subdirectories, use the ‘-r’ option with ‘grep’:

$ grep -r "abcd" *

Example 8: Inverting Matches 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

Example 9: Displaying Lines that Match Multiple Patterns

We can specify different patterns using multiple ‘-e’ options. In this example, we’re using ‘ifconfig’ and ‘grep’ to display lines that match both ‘lo’ and ‘eth0’:

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

Example 10: Display the lines which do not match all the given patterns

Similar to Example 9, you can use multiple ‘-e’ options to specify different patterns. In this case, we’re using ‘ifconfig’ and ‘grep’ to display lines that do not match both ‘lo’ and ‘eth0’:

$ 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)

Example 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 to count the lines that do not match the pattern or string.

$ ifconfig | grep -vc inet
14

Example 12: Displaying Only the File Names Matching a Pattern

When you provide multiple files as input to ‘grep,’ it displays the names of files containing text that matches the pattern. This is especially useful when searching for notes across your entire directory structure.

$ grep -l this demo_*
demo_file
demo_file1

Example 13: Showing 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

Example 14: Showing the Position of a Match in the Line

To display the byte offset of a match in the line, use the ‘-b’ option with grep command:

$ 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.

Example 15: Showing Line Numbers Using ‘grep -n’

To display line numbers while showing the output, use ‘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.

If you find any mistake above, kindly email to [email protected]

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 & discussions at Telegram SanfoundryClasses.