Introduction
This guide details the most useful grep commands for Linux / Unix systems.
After going through all the commands and examples, you will learn how to use grep to search files for a text from the terminal.
Prerequisites
- Linux or UNIX-like system
- Access to a terminal/command line
- A user with permissions to access the desired files and directories
Note: A line does not represent a line of text as viewed on the terminal screen. A line in a text file is a sequence of characters until a line break is introduced. The output of grep commands may contain whole paragraphs unless the search options are refined.
What is the grep Command?
Grep is an acronym that stands for Global Regular Expression Print.
Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified file. The text search pattern is called a regular expression. When it finds a match, it prints the line with the result. The grep command is handy when searching through large log files.
Using the grep Command
The grep command consists of three parts in its most basic form. The first part starts with grep
, followed by the pattern that you are searching for. After the string comes the file name that the grep searches through.
The simplest grep command syntax looks like this:
The command can contain many options, pattern variations, and file names. Combine as many options as necessary to get the results you need. Below are the most common grep commands with examples.
Note: Grep is case-sensitive. Make sure to use the correct case when running grep commands.
To Search a File
To print any line from a file that contains a specific pattern of characters, in our case phoenix
in the file sample2
, run the command:
grep phoenix sample2
Grep will display every line where there is a match for the word phoenix
. When executing this command, you do not get exact matches. Instead, the terminal prints the lines with words containing the string of characters you entered. Here is an example:
Tip: If your search pattern includes characters other than alphanumeric, use quotation marks. This includes blank spaces or any symbol.
To Search Multiple Files
To search multiple files with the grep command, insert the filenames you want to search, separated with a space character.
In our case, the grep command to match the word phoenix
in three files sample
, sample2
, and sample3
looks like this example:
grep phoenix sample sample2 sample3
The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters.
You can append as many filenames as needed. The terminal prints a new line with the filename for every match it finds in the listed files.
Tip: Refer to our article Xargs Commands to learn how to use xargs with grep to search for a string in the list of files.
Search All Files in Directory
To search all files in the current directory, use an asterisk instead of a filename at the end of a grep command.
In this example, we use nix as a search criterion:
grep nix *
The output shows the name of the file with nix and returns the entire line.
To Find Whole Words Only
Grep allows you to find and print the results for whole words only. To search for the word phoenix in all files in the current directory, append -w to the grep command.
grep -w phoenix *
This option only prints the lines with whole-word matches and the names of the files it found them in:
When -w
is omitted, grep displays the search pattern even if it is a substring of another word.
If you would like to search for multiple strings and word patterns, check out our article on how to grep for multiple strings, patterns or words.
To Ignore Case in Grep Searches
As grep commands are case sensitive, one of the most useful operators for grep searches is -i. Instead of printing lowercase results only, the terminal displays both uppercase and lowercase results. The output includes lines with mixed case entries.
An example of this command:
grep -i phoenix *
If we use the -i operator
to search files in the current directory for phoenix
, the output looks like this:
To Search Subdirectories
To include all subdirectories in a search, add the -r operator to the grep command.
grep -r phoenix *
This command prints the matches for all files in the current directory, subdirectories, and the exact path with the filename. In the example below, we also added the -w
operator to show whole words, but the output form is the same.
Inverse grep Search
You can use grep to print all lines that do not match a specific pattern of characters. To invert the search, append -v
to a grep command.
To exclude all lines that contain phoenix
, enter:
grep -v phoenix sample
The terminal prints all lines that do not contain the word used as a search criterion. Use -i
to ignore case to exclude completely the word used for this search:
To Show Lines That Exactly Match a Search String
The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option.
grep -x “phoenix number3” *
The output shows only the lines with the exact match. If there are any other words or characters in the same line, the grep does not include it in the search results. Do not forget to use quotation marks whenever there is a space or a symbol in a search pattern.
Here is a comparison of the results without and with the -x
operator in our grep command:
To List Names of Matching Files
Sometimes, you only need to see the names of the files that contain a word or string of characters and exclude the actual lines. To print only the filenames that match your search, use the -l operator:
grep -l phoenix *
The output shows the exact filenames that contain phoenix
in the current directory but does not print the lines with the corresponding word:
As a reminder, use the recursive search operator -r
to include all subdirectories in your search.
To Count the Number of Matches
Grep can display the filenames and the count of lines where it finds a match for your word.
Use the -c operator to count the number of matches:
grep -c phoenix *
To Display the Number of Lines Before or After a Search String
Sometimes you need more content in search results to decide what is most relevant.
Use the following operators to add the desired lines before, after a match, or both:
- Use -A and a number of lines to display after a match:
grep -A 3 phoenix sample
— this command prints three lines after the match. - Use -B and a number of lines to display before a match:
grep -B 2 phoenix sample
— this command prints two lines before the match. - Use -C and a number of lines to display before and after the match:
grep -C 2 phoenix sample
— this command prints two lines before and after the match.
To Display Line Numbers with grep Matches
When grep prints results with many matches, it comes handy to see the line numbers. Append the -n operator to any grep command to show the line numbers.
We will search for Phoenix in the current directory, show two lines before and after the matches along with their line numbers.
grep -n -C 2 Phoenix sample
Limit grep Output to a Fixed Number of Lines
Individual files, such as log files, can contain many matches for grep search patterns. Limit the number of lines in the grep output by adding the -m option and a number to the command.
grep -m2 Phoenix sample
In this case, the terminal prints the first two matches it finds in the sample
file.
If you do not specify a file and search all files in a directory, the output prints the first two results from every file along with the filename that contains the matches.
Conclusion
Now you know how to use the grep
command in Linux/Unix.
The grep command is highly flexible with many useful operators and options. By combining grep commands, you can get powerful results and find the text hiding in thousands of files. To get started, check out our grep regex guide article.
By default, most search tools look at file names, not file contents. However, the most famous GNU search program, grep
, will look inside files with the correct flags. Here we show you how you can find specific word(s) in a file on Linux.
Content
- Using grep to Find a Specific Word in a File
- Using find to Find a Specific Word in a File
- Using ack to Find a Specific Word in a File
- Want a GUI? Use Catfish
- Frequently Asked Questions
By default, grep searches through the contents of files as well as their file names. It’s included on the majority of Linux systems and is generally identical across distros. Programmers looking through the file contents of their projects might prefer to run a different command, like ack
.
Depending on how the file is encoded, grep
may not always be able to look inside. But for most text-based formats, grep
can scan the text of the file for the specified pattern.
grep -rw '/path/to/search/' -e 'pattern'
- The
-r
flag sets grep to recursive mode, navigating through all the directories contained within the specified directory. - The
-w
flag searches for whole word matches. This means that “red” will match only the actual word “red” rather than any string of letters containing it, like “redundant” or “tired.” It does this by looking only for “red” surrounded by what is known as non-word constituent characters (i.e., anything that isn’t a letter, number or underscore). - The
-e
flag prefaces the pattern to search for. It supports regular expressions by default.
To speed up grep, you can use the --exclude
and --include
flags to limit the search to certain types of files. For example, --exclude='*.csv'
will not search within any files with the .csv extension. --include='*.txt'
, on the other hand, will only search within files with the .txt extension. The flag can be added immediately after the grep command as shown below:
grep --exclude='*.csv' -Rw '/path/to/search' -e 'pattern'
You can also exclude specified directories by following the format below:
grep --exclude-dir='{dir1,dir2,*_old}' -Rw '/path/to/search' -e 'pattern'
This command will not search in any directories in the present working directory named dir1, dir2, or matching the pattern *_old, eliminating them from the search process. It will execute the specified recursive, full-word match search on all other files in the present working directory.
Interesting Flags You Can Use With grep
Now that you have been properly acquainted with grep and how it works, here are some useful flags you can attach to your command:
-i
– Makes grep do a non-case-sensitive search. For example, searching for “Kraken” will return a result when grep finds matches for “kraken” or “kRaken”.-n
– Show line numbers next to matches. This is especially useful for programmers or people looking through large config files.-R
– As with-r
, grep will do a recursive search through all subfolders, but this specific flag will follow symbolic links (shortcuts).-s
– Suppresses error messages. If you’re getting many distracting errors about files that don’t exist, can’t be read, or have inappropriate permissions, pass this so that grep can stick to showing you matches it finds.
Using find to Find a Specific Word in a File
While the find
command’s syntax is more complicated than grep, some prefer it.
find . -name "*.php" -exec grep "pattern" {} ;
This command will use find’s -exec
flag to pass the found files to grep for searching. With a clever arrangement of syntax, you can use find
‘s faster file-system search to locate the specific file types you want to search within, then pipe them to grep
to search inside the files.
Note that find
only looks at filenames, not contents. That’s why grep is required to search file text and contents. The normal grep flags should be fully operational from within the -exec
flag.
Using ack to Find a Specific Word in a File
The ack command is likely the fastest searching tool, but it’s not as popular as grep
. The command below will search within the current directory.
If you want to search within a specific file or directory, you can append that file or fully-qualified pathname to your search.
ack 'pattern' /path/to/file.txt
Want a GUI? Use Catfish
If you’re allergic to terminals, all the popular Linux distros offer Catfish, a versatile GUI application that allows you to search files and their contents for a specific string. It isn’t as advanced as the commands discussed here, but it provides a valuable service to people who would prefer a graphical interface.
To search file contents for a specific word, click the menu on the top-right corner of Catfish and click on “Search file contents.”
After you’ve set it up, type what you want to search for in the top bar and press Enter. That’s it!
Frequently Asked Questions
How do I stop a grep search before it’s done?
To stop any ongoing process in your terminal, simply press Ctrl + C on your keyboard. This sends a signal to terminate the running process. It’s also why you can’t use normal copy/paste shortcuts from within a terminal emulator.
Are there any file managers that search file contents?
If you use the KDE Plasma desktop environment, its default file manager (Dolphin) already has this capability. When you click the search button to look for files, there’s an option to choose between file names and file content underneath the search bar.
Just click on “Content” if you want to search for words within files. It won’t be as advanced as using grep, but it does the job.
Are there other uses for grep?
Grep isn’t just for searching your file system! Interestingly enough, you can pipe it through almost any command to search through its output instead of having to manually find something yourself.
Grep can be used to filter command output to show you things that are more relevant to you. Experiment enough with it and you’ll eventually master the art of diagnosing and getting to know your computer!
All screenshots by Miguel Leiva-Gomez.
Miguel Leiva-Gomez
Miguel has been a business growth and technology expert for more than a decade and has written software for even longer. From his little castle in Romania, he presents cold and analytical perspectives to things that affect the tech world.
Subscribe to our newsletter!
Our latest tutorials delivered straight to your inbox
grep
(GNU or BSD)
You can use grep
tool to search recursively the current folder, like:
grep -r "class foo" .
Note: -r
— Recursively search subdirectories.
You can also use globbing syntax to search within specific files such as:
grep "class foo" **/*.c
Note: By using globbing option (**
), it scans all the files recursively with specific extension or pattern. To enable this syntax, run: shopt -s globstar
. You may also use **/*.*
for all files (excluding hidden and without extension) or any other pattern.
If you’ve the error that your argument is too long, consider narrowing down your search, or use find
syntax instead such as:
find . -name "*.php" -execdir grep -nH --color=auto foo {} ';'
Alternatively, use ripgrep
.
ripgrep
If you’re working on larger projects or big files, you should use ripgrep
instead, like:
rg "class foo" .
Checkout the docs, installation steps or source code on the GitHub project page.
It’s much quicker than any other tool like GNU/BSD grep
, ucg
, ag
, sift
, ack
, pt
or similar, since it is built on top of Rust’s regex engine which uses finite automata, SIMD and aggressive literal optimizations to make searching very fast.
It supports ignore patterns specified in .gitignore
files, so a single file path can be matched against multiple glob patterns simultaneously.
You can use common parameters such as:
-i
— Insensitive searching.-I
— Ignore the binary files.-w
— Search for the whole words (in the opposite of partial word matching).-n
— Show the line of your match.-C
/--context
(e.g.-C5
) — Increases context, so you see the surrounding code.--color=auto
— Mark up the matching text.-H
— Displays filename where the text is found.-c
— Displays count of matching lines. Can be combined with-H
.
Do you want to find all files that contain a particular word or string of text on your entire Linux system or a given directory. This article will guide you on how to do that, you will learn how to recursively dig through directories to find and list all files that contain a given string of text.
A simple way to work this out is by using grep pattern searching tool, is a powerful, efficient, reliable and most popular command-line utility for finding patterns and words from files or directories on Unix-like systems.
Read Also: 11 Advanced Linux ‘Grep’ Commands on Character Classes and Bracket Expressions
The command below will list all files containing a line with the text “check_root”, by recursively and aggressively searching the ~/bin
directory.
$ grep -Rw ~/bin/ -e 'check_root'
Where the -R
option tells grep to read all files under each directory, recursively, following symbolic links only if they are on the command line and option -w instructs it to select only those lines containing matches that form whole words, and -e
is used to specify the string (pattern) to be searched.
You should use the sudo command when searching certain directories or files that require root permissions (unless you are managing your system with the root account).
$ sudo grep -Rw / -e 'check_root'
To ignore case distinctions employ the -i
option as shown:
$ grep -Riw ~/bin/ -e 'check_root'
If you want to know the exact line where the string of text exist, include the -n
option.
$ grep -Rinw ~/bin/ -e 'check_root'
Assuming there are several types of files in a directory you wish to search in, you can also specify the type of files to be searched for instance, by their extension using the --include
option.
This example instructs grep to only look through all .sh
files.
$ grep -Rnw --include=*.sh ~/bin/ -e 'check_root'
In addition, it is possible to search for more than one pattern, using the following command.
$ grep -Rinw ~/bin/ -e 'check_root' -e 'netstat'
That’s It! If you know any other command-line trick to find string or word in files, do share with us or ask any questions regarding this topic, use the comment form below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
This tutorial focuses on finding text in files using the grep command and regular expressions.
When working on a Linux system, finding text in files is a very common task done by system administrators every day.
You may want to search for specific lines in a log file in order to troubleshoot servers issues.
In some cases, you are interested in finding actions done by specific users or you want to restrict lines of a big file to a couple of lines.
Luckily for you, there are multiple ways of finding text into files on Linux but the most popular command is the grep command.
Developed by Ken Thompson in the early days of Unix, grep (globally search a regular expression and print) has been used for more than 45 years by system administrators all over the world.
In this tutorial, we will focus on the grep command and how it can help us effectively find text in files all over our system.
Ready?
Grep Syntax on Linux
As specified above, in order to find text in files on Linux, you have to use the grep command with the following syntax
$ grep <option> <expression> <path>
Note that the options and the path are optional.
Before listing and detailing all the options provided by grep, let’s have a quick way to memorize the syntax of the grep command.
In order to remember the syntax of the grep command, just remember that grep can be written as grEP which means that the expression comes before the path.
This is a great way to remember the grep syntax and the find syntax at the same time but the find syntax is the exact opposite : path first and expression after.
Quick grep examples
There are complex options that can be used with grep, but let’s start with a set of very quick examples.
Listing users using grep
On Linux, as you already probably know it, user accounts are listed in a specific file called the passwd file.
In order to find the root account in a specific file, simply enter your text and the file you want to search into.
$ grep root /etc/passwd root:x:0:0:root:/root:/bin/bash
Another very popular way of using the grep command is to look for a specific process on your Linux system.
Filtering Processes using grep
As explained in one of our previous tutorials, you have to use the “ps” command in order to list all the processes currently running on your system.
You can pipe the “ps” command with the “grep” command in order to filter the processes you are interested in.
$ ps aux | grep <process>
If you are interested in bash processes for example, you can type the following command
$ ps aux | grep bash root 1230 0.0 0.0 23068 1640 tty1 S+ Jan11 0:00 -bash user 2353 0.0 0.1 23340 5156 pts/0 Ss 03:32 0:00 -bash user 2473 0.0 0.0 14856 1056 pts/0 S+ 03:45 0:00 grep --color=auto bash user 6685 0.0 0.0 23140 1688 pts/2 Ss+ Nov09 0:00 bash
Note : if you are not sure about how to use pipes on Linux, here’s a complete guide on input and output redirection.
Inspecting Linux Kernel logs with grep
Another great usage of the grep command is to inspect the Linux Kernel buffer ring.
This is heavily used when performing troubleshooting operations on Linux systems because the kernel will write to its buffer ring when starting or booting up.
Let’s say for example that you introduced a new disk into your system and you are not sure about the name given to this new disk.
In order to find out this information, you can use the “dmesg” command and pipe it to the grep command.
$ dmesg | grep -E sd.{1}
Grep Command Options
The grep command is very useful by itself but it is even more useful when used with options.
The grep command literally has a ton of different options.
The following sections will serve as a guide in order to use those options properly and examples will be given along the way.
- How To Find Last Login on Linux
- How To Zip Folder on Linux
- How To Install and Enable SSH Server on Ubuntu 20.04
Search specific string using grep
In some cases, you may interested in finding a very specific string or text into a file.
In order to restrict the text search to a specific string, you have to use quotes before and after your search term.
$ grep "This is a specific text" .
To illustrate this option, let’s pretend that you are looking for a specific username on your system.
As many usernames may start with the same prefix, you have to search for the user using quotes.
$ grep "devconnected" /etc/passwd
Search text using regular expressions
One of the greatest features of the grep command is the ability to search for text using regular expressions.
Regular expressions are definitely a great tool to master : they allow users to search for text based on patterns like text starting with a specific letters or text that can be defined as an email address.
Grep supports two kinds of regular expressions : basic and extended regular expressions.
Basic Regular Expressions (BRE)
The main difference between basic and extended regular expressions is the fact that you can use regular expressions symbols with BRE (basic regular expressions) but they will have to be preceded by a backslash.
Most common regular expression patterns are detailed below with examples :
- ^ symbol : also called the caret symbol, this little hat symbol is used in order to define the beginning of a line. As a consequence, any text after the caret symbol will be matched with lines starting by this text.
For example, in order to find all drives starting with “sd” (also called SCSI disks), you can use the caret symbol with grep.
$ lsblk | grep "^sb"
- $ symbol : the dollar sign is the opposite of the caret symbol, it is used in order to define the end of the line. As a consequence, the pattern matching will stop right before the dollar sign. This is particularly useful when you want to target a specific term.
In order to see all users having bash shell on your system, you could type the following command
$ cat /etc/passwd | grep "bash$"
- (dot symbol) : the dot symbol is used to match one single character in a regular expression. This can be particularly handy when search terms contain the same letters at the beginning and at the end but not in the middle.
If for example, you have two users on your system, one named “bob” and one named “bab”, you could find both users by using the dot symbol.
$ cat /etc/passwd | grep "b.b"
- [ ] (brackets symbol) : this symbol is used to match only a subset of characters. If you want to only match “a”, or “o”, or “e” characters, you would enclose them in brackets.
Back to the “bob” example, if you want to limit your search to “bob” and “bab”, you could type the following command
$ cat /etc/passwd | grep "b[ao]b"
Using all the options provided before, it is possible to isolate single words in a file : by combining the caret symbol with the dollar symbol.
$ grep "^word$" <file|path>
Luckily for you, you don’t have to type those characters every time that you want to search for single word entries.
You can use the “-w” option instead.
$ grep -w <expression> <file|path>
Extended Regular Expressions (ERE)
Extended regular expressions as its name states are regular expressions that are using more complex expressions in order to match strings.
You can use extended regular expressions in order to build an expression that is going to match an email address for example.
In order to find text in files using extended regular expressions, you have to use the “-E” option.
$ grep -E <expression> <path>
One great usage of the extended regular expressions is the ability to search for multiple search terms for example.
Searching multiple strings in a file
In order to search for multiple strings in a file, use the “-E” option and put your different search terms separated by straight lines (standing for OR operators in regular expressions)
$ grep -E "text1|text2|text3" <path>
Back to our previous grep example, you could find the root account and the bob account using extended regular expressions.
$ grep -E "root|bob" /etc/passwd
Search for IP addresses using grep
In some cases, you may want to isolate IP addresses in a single file : using extended regular expressions is a great way of finding IP addresses easily.
Plenty of different websites provide ready-to-use regular expressions : we are going to use this one for IP addresses.
"b([0-9]{1,3}.){3}[0-9]{1,3}b"
How would you read this regular expression?
An IP address is made of 4 3-digit numbers separated by dots, this is exactly what this regular expression describes.
([0-9]{1,3}.){3} = 3 3-digits numbers separated by dots [0-9]{1,3} = the last 3-digits number ending the IP address
Here is how you would search for IP addresses using the grep command
grep -E "b([0-9]{1,3}.){3}[0-9]{1,3}b" <file|path>
Search for URL addresses using grep
Similarly, it is entirely possible to search for URL addresses in a file if you are working with website administration on a daily basis.
Again, many websites provide regular expressions for URLs, but we are going to use this one.
grep -E '(http|https)://[^/"]+' <file|path>
Search for email addresses using grep
Finally, it is possible to search for email addresses using extended regular expressions.
To find email adresses, you are going to use the following regular expression
grep -E "b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,6}b" <file|path>
Now that you have seen how to use extended regular expressions with grep, let’s see how you can recursively find text in a file using options.
Find Text Recursively with grep
In order to find text recursively (meaning exploring every directory and its children) on Linux, you have to use “grep” with the “-r” option (for recursive)
$ grep -R <expression> <path>
For example, to search for all files containing the word “log” in the /var/log directory, you would type
$ grep -R "log$" /var/log
Using this command, it is very likely that you will see a lot of entries with permission denied.
In order to ignore those permission denied entries, redirect the output of your command to /dev/null
$ grep -R "log$" /var/log 2> /dev/null
In order to find text recursively, you can also use the “-d” option with the “recurse” action.
$ grep -d recurse "log$" /var/log
Searching text recursively can be pretty handy when you are trying to find specific configuration files on your system.
Printing line numbers with grep
As you can see in our previous examples, we were able to isolate lines matching the pattern specified.
Over, if files contain thousands of lines, it would be painful identifying the file but not the line number.
Luckily for you, the grep option has an option in order to print line numbers along with the different matches.
To display line numbers using grep, simply use the “-n” option.
$ grep -n <expression> <path>
Going back to our user list example, if we want to know on which line those entries are, we would type
$ grep -n -E "root|bob" /etc/passwd
Find text with grep using case insensitive option>
In some cases, you may not be sure if the text is written with uppercase or lowercase letters.
Luckily for you, the grep command has an option in order to search for text in files using a case insensitive option.
To search for text using the case insensitive option, simply use the “-i” option.
$ grep -i <expression> <path>
Exclude patterns from grep
Grep is used as a way to identify files containing a specific files, but what if you wanted to do the exact opposite?
What if you wanted to find files not containing a specific string on your Linux system?
This is the whole purpose of the invert search option of grep.
To exclude files containing a specific string, use “grep” with the “-v” option.
$ grep -v <expression> <file|path>
As a little example, let’s say that you have three files but two of them contain the word “log”.
In order to exclude those files, you would have to perform an invert match with the “-v” option.
Show filenames using grep
In some cases, you are not interested in finding text inside files, but only in their filenames.
In order to print only filenames, and not the filename with the actual output, use the “-l” option.
$ grep -l <expression> <path>
Using our previous example, we would not get the content of the file, but only the filename.
Conclusion
In this tutorial, you learnt how you can easily find text in files on Linux.
You learnt that you can use many different options : basic regular expressions or more advanced (extended) regular expressions if you are looking to match IP addresses or phone numbers for example.
You also discovered that you can perform inverse lookups in order to find files not matching a specific pattern on your system.
If you are interested in Linux system administration, we have a complete section dedicated to it on the website, so make sure to have a look!