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
.
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.
grep
(GNU or BSD)
You can use grep
tool to search recursively the current folder with -r
parameter, like:
grep -r "pattern" .
Note: -r
— Recursively search subdirectories.
To search within specific files, you can use a globbing syntax 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 "pattern" .
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 the common parameters such as:
-i
— Insensitive searching.-I
— Ignore the binary files.-w
— Search for the whole words (in 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
.
Introduction
The grep
command, which stands for «global regular expression print,» is one of Linux’s most powerful and widely used commands.
grep
looks for lines that match a pattern in one or more input files and outputs each matching line to standard output. grep
reads from the standard input, which is usually the output of another command, if no files are specified.
In this tutorial, you will use grep
command that looks for lines that match a pattern in one or more input files and outputs.
grep
Command Syntax
The grep command has the following syntax:
grep [OPTIONS] PATTERN [FILE...]
Optional items are those in square brackets.
File
— Names of one or more input files.PATTERN
— Look for a pattern.OPTIONS
— A set of zero or more choices.grep
has a lot of settings that govern how it behaves.The user performing the command must have read access to the file in order to search it.
In Files, Look for a String
The grep
command’s most basic use is to look for a string (text) in a file.
For example, to see all the entries in the /etc/passwd
file that contains the string bash
, use the following command:
grep bash /etc/passwd
This is what the output should look like:
root:x:0:0:root:/root:/bin/bash
vega:x:1000:1000:vega:/home/vega:/bin/bash
If the string contains spaces, use single or double quotation marks to surround it:
grep "Gnome Display Manager" /etc/passwd
Invert Match (Exclude)
Use the -v
(or --invert-match
) option to display lines that do not match a pattern.
To print the lines that do not contain the string nologin
, for example, type:
grep -v nologin /etc/passwd
Output
root:x:0:0:root:/root:/bin/bash
colord:x:124:124::/var/lib/colord:/bin/false
git:x:994:994:git daemon user:/:/usr/bin/git-shell
vega:x:1000:1000:vega:/home/vega:/bin/bash
Use Grep to Filter the Output of a Command
The output of a command can be filtered using grep
and pipe
, with just the lines matching a specific pattern being printed on the terminal.
You can use the ps
command to see which processes are running on your system as user www-data
, for example:
ps -ef | grep www-data
Output
www-data 18247 12675 4 16:00 ? 00:00:00 php-fpm: pool www
root 18272 17714 0 16:00 pts/0 00:00:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn www-data
www-data 31147 12770 0 Oct22 ? 00:05:51 nginx: worker process
www-data 31148 12770 0 Oct22 ? 00:00:00 nginx: cache manager process
You can also use a single command to bring in several pipes. There is also a line in the output above that contains the grep
process, as you can see. Pass the output to another grep
instance as described below if you don’t want that line to be displayed.
ps -ef | grep www-data | grep -v grep
Output
www-data 18247 12675 4 16:00 ? 00:00:00 php-fpm: pool www
www-data 31147 12770 0 Oct22 ? 00:05:51 nginx: worker process
www-data 31148 12770 0 Oct22 ? 00:00:00 nginx: cache manager process
Recursive Search
Invoke grep
with the -r
option to recursively search for a pattern (or --recursive
). When this option is supplied, grep
will scan all files in the specified directory, skipping any recursively encountered symlinks.
Instead of -r
, use the -R
option to follow all symbolic links (or --dereference-recursive
).
Here’s an example of how to search all files in the /etc
directory for the string vegastack.com
:
grep -r vegastack.com /etc
You will get an output like below:
Output
/etc/hosts:127.0.0.1 node2.vegastack.com
/etc/nginx/sites-available/vegastack.com: server_name vegastack.com www.vegastack.com;
grep
will follow all symbolic links if you use the -R
option:
grep -R vegastack.com /etc
Take note of the output’s last line. Because files in Nginx’s sites-enabled directory are symlinks to configuration files in the sites-available directory, that line is not shown when grep
is run with -r
.
Output
/etc/hosts:127.0.0.1 node2.vegastack.com
/etc/nginx/sites-available/vegastack.com: server_name vegastack.com www.vegastack.com;
/etc/nginx/sites-enabled/vegastack.com: server_name vegastack.com www.vegastack.com;
Show Only the Filename
Use the -l
(or --files-with-matches
) option to suppress the default grep
output and only print the names of files containing the matched pattern.
The command below searches the current working directory for all files ending in .conf
and prints just the names of the files that contain the string vegastack.com:
grep -l vegastack.com *.conf
You will get an output like below:
tmux.conf
haproxy.conf
Usually, the -l
option is combined with the recursive option -R
:
grep -Rl vegastack.com /tmp
Case Insensitive Search
grep
is case-sensitive by default. The uppercase and lowercase characters are treated separately in this scenario.
When using grep
, use the -i
option to ignore case when searching (or --ignore-case
).
When searching for Zebra without any options, for example, the following command will not return any results, despite the fact that there are matching lines:
grep Zebra /usr/share/words
However, if you use the -i
option to perform a case-insensitive search, it will match both upper and lower case letters:
grep -i Zebra /usr/share/words
«Zebra» will match «zebra», «ZEbrA», or any other upper and lower case letter combination for that string.
zebra
zebra's
zebras
Search for Full Words
grep
will display all lines where the string is embedded in larger strings while searching for a string.
If you search for «gnu,» for example, you’ll find all lines where «gnu» is embedded in larger terms like «cygnus» or «magnum»:
grep gnu /usr/share/words
Output
cygnus
gnu
interregnum
lgnu9d
lignum
magnum
magnuson
sphagnum
wingnut
Use the -w
(or --word-regexp
) option to return only lines where the provided string is a whole word (contained by non-word characters).
🤔
Alphanumeric characters (a-z, A-Z, and 0-9) and underscores (_) make up word characters. Non-word characters are all the rest of the characters.
If you execute the same program with the -w
option, the grep
command will only return lines that contain the word gnu as a distinct word.
grep -w gnu /usr/share/words
Output
gnu
Show Line Numbers
The -n
(or --line-number
) option instructs grep
to display the line number of lines containing a pattern-matching string. grep
prints the matches to standard output, prefixed with the line number, when this option is used.
You may use the following command to display the lines from the /etc/services
file containing the string bash prefixed with the corresponding line number:
grep -n 10000 /etc/services
The matches are found on lines 10123 and 10124, as seen in the output below.
Output
10123:ndmp 10000/tcp
10124:ndmp 10000/udp
Count Matches
Use the -c
(or --count
) option to print a count of matching lines to standard output.
We’re measuring the number of accounts that use /usr/bin/zsh
as a shell in the example below.
regular expression
grep -c '/usr/bin/zsh' /etc/passwd
Output
4
Quiet Mode
The -q
(or --quiet
) option instructs grep
to execute in silent mode, with no output to the standard output. The command leaves with status 0
if a match is found. This is handy when using grep
in shell scripts to check if a file contains a string and then conduct a specific action based on the result.
Here’s an example of using grep
as a test command in an if statement in quiet mode:
if grep -q PATTERN filename
then
echo pattern found
else
echo pattern not found
fi
Basic Regular Expression
Basic, Extended, and Perl-compatible regular expression feature sets are available in GNU Grep.
grep
interprets the pattern as a basic regular expression by default, with all characters except the meta-characters being regular expressions that match each other.
The following is a list of the most prevalent meta-characters:
- To match a phrase at the beginning of a line, use the
^
(caret) symbol. The string kangaroo will only match in the following example if it appears at the very beginning of a line.
grep "^kangaroo" file.txt
- To match an expression at the end of a line, use the $ (dollar) sign. In the example below, the string kangaroo will only match if it appears at the end of a line.
grep "kangaroo$" file.txt
- To match a single character, use the
.
(period) sign. For example, you could use the following pattern to match anything that starts with kan, then has two characters, and ends with the string roo:
grep "kan..roo" file.txt
- To match any single character wrapped in brackets, use
[]
(brackets). To discover the lines that contain the words «accept» or «accent,» apply the following pattern:
grep "acce[np]t" file.txt
- To match any single character that isn’t enclosed in brackets, use
[]
. The following pattern will match any combination of strings containing co(any letter except l) a, such as coca, cobalt, and so on, but not cola.
grep "co[^l]a" file.txt
Use the (backslash) symbol to get around the next character’s specific meaning.
Extended Regular Expressions
Use the -E
(or --extended-regexp
) option to interpret the pattern as an extended regular expression. To generate more complicated and powerful search patterns, extended regular expressions include all of the fundamental meta-characters as well as additional meta-characters. Here are a few examples:
- All email addresses in a given file are matched and extracted:
grep -E -o "b[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+.[A-Za-z]{2,6}b" file.txt
- From a given file, find and extract all valid IP addresses:
grep -E -o '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' file.txt
Only the matching string is printed using the -o
option.
Search for Multiple Strings (Patterns)
The OR operator |
can be used to connect two or more search patterns.
grep
reads the pattern as a normal regular expression by default, which means that meta-characters like |
lose their special significance and should be replaced with their backslashed variants.
We’re looking for all occurrences of the words fatal, error, and critical in the Nginx log error file in the example below:
grep 'fatal|error|critical' /var/log/nginx/error.log
The operator |
should not be escaped if you use the extended regular expression option -E
, as demonstrated below:
grep -E 'fatal|error|critical' /var/log/nginx/error.log
Print Lines Before a Match
Use the -B
(or --before-context
) option to print a certain number of lines before matching lines.
For example, you could use the following command to display five lines of leading context before matching lines:
grep -B 5 root /etc/passwd
Print Lines After a Match
Use the -A
(or --after-context
) option to output a certain number of lines following matching lines.
For example, you could use the following command to display five lines of trailing context after matching lines:
grep -A 5 root /etc/passwd
Conclusion
You can use the grep
command to look for a pattern within files. If grep
finds a match, it outputs the lines that contain the provided pattern.
The Grep User’s Manual page has a lot more information on grep
.
If you have any queries, please leave a comment below and we’ll be happy to respond to them.
This tutorial will teach you how to recursively search for files containing a specific string on Linux using the command line. This tutorial uses the ‘grep’ command to search for strings in files. Alternatively, you may use the find command to look for files with specific content.
A basic syntax for searching text with grep command:
grep —rl «search-string» /path/to/serch/dir |
The grep command offers other useful options for finding specific text in file systems.
-r, --recursive
: Search files recursively-R, --dereference-recursive
: Search files recursively and follow symlinks--include=FILE_PATTERN
: search only files that match FILE_PATTERN--exclude=FILE_PATTERN
: skip files and directories matching FILE_PATTERN--exclude-from=FILE
: skip files matching any file pattern from FILE--exclude-dir=PATTERN
: directories that match PATTERN will be skipped.-L, --files-without-match
: Print file names containing no match-l, --files-with-matches
: Print string containing file names only-i, --ignore-case
: ignore case of search string-e, --regexp=PATTERN
: Use a pattern to search or specify multiple search strings-w, --word-regexp
: force to match whole words
There are several ways to use the grep command to search text. Let’s discuss a few examples of searching a text/string in the file system.
- Search Single String in All Files
- Search Multiple String in All Files
- Search String in Specific Files
- Exclude Some Files from Search
- Exclude Some Directories from Search
The below example command will search the string “Error” in all files in /var/log directory and its sub-directories.
grep -rlw "Error" /var/log
The -e
switch can also be utilized to find multiple strings. This is comparable to the egrep
program. The example below will look for “Error” and “Warning” in all the files in the /var/log directory and its subdirectories.
grep -rlw -e "Error" -e "Warning" /var/log
You can search strings in files that match the file name criteria. The following command searches for “Error” in files with the .log extension in the /var/log directory and its sub-directories.
grep -rlw --include="*.log" -e "Error" /var/log
You can use the --exclude
option in find to exclude some files that match certain file name criteria. For example, you can exclude files with the .txt extension.
grep -rlw --exclude="*.txt" -e "tecadmin" /var/log
You can also skip searching certain directories. For instance, don’t search for string files in any folder with apache2 in its name.
grep -rlw --exclude-dir="*apache2*" -e "tecadmin" /var/log
Conclusion
You have learned how to search for specific text in files on the Linux file system in this tutorial.