grep command which means “print global regular expressionOne of the most powerful and widely used commands on Linux.
Grep searches one or more input files for lines that match the specified pattern and writes each line that matches the standard output. If no file is specified, grep reads from the standard input which is usually the result of another command.
In this tutorial, we’ll show you how to use the grep command with practical examples and step-by-step explanations of the most popular GNU grep options.
Command Form Grep Perintah
Before discussing how to use the Grep command, let’s start by reviewing the basic syntax.
The Grep utility expression takes the following form:
grep [OPTIONS] PATTERN [FILE...]
Items in parentheses are optional.
OPTIONS
Grep provides a number of options that control its behavior.PATTERN
Search mode.FILE
Zero or more input file names.
How to use Grep to find strings in files
The primary use of the grep command is to search for strings (text) in files.
For example, to display lines from a file /etc/passwd
which contains the bash string, you can use the following command:
grep bash /etc/passwd
The output will look like this:
root❌0:0:root:/root:/bin/bash linux❌1000:1000:linux:/home/linux:/bin/bash
If the string contains spaces, you must enclose them in single or double quotes:
grep "Gnome Display Manager" /etc/passwd
Grep Reverse Match (Exception)
To display fonts that do not match the pattern, use the options -v
(or --invert-match
).
For example to display the lines from the /etc/passwd file that does not contain strings nologin.
You can use the following command:
grep -v nologin /etc/passwd
root❌0:0:root:/root:/bin/bash colord❌124:124::/var/lib/colord:/bin/false git❌994:994:git daemon user:/:/usr/bin/git-shell linux❌1000:1000:linux:/home/linux:/bin/bash
Grep to search string in command output
Alternatively, if you specify an input file, you can pipe the output of another command to grep, and then output only lines that match the specified pattern.
For example, to see which process is running on your system as a user www-data
you can use the following command:
ps -ef | grep www-data
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 connect several tubes in command. As you can see in the above output there is also a line containing the grep process. If you don’t want this line to appear, pass the output to another grep instance as shown below.
ps -ef | grep www-data | grep -v grep
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
Grep: iterative task
To search for patterns frequently, use the options -r
(or --recursive
). This method will search all files in the specified directory, skipping any symbolic links you encounter frequently. To follow all symbolic links, use the options -R
(or --dereference-recursive
).
In the following example, we are looking for a string example.com
In all files in the directory /etc
:
grep -r example.com /etc
The command will print matching lines preceded by the full path of the file.
/etc/hosts:127.0.0.1 node2.example.com /etc/nginx/sites-available/example.com: server_name example.com www.example.com;
If instead of using -r
you are using options -R
grep will follow all symbolic links:
grep -R example.com /etc
Note the last line of the output. This line was not printed in the above example because the file is in the directory sites-enabled
Nginx is a symbolic link to a configuration file in a directory sites-available
.
/etc/hosts:127.0.0.1 node2.example.com /etc/nginx/sites-available/example.com: server_name example.com www.example.com; /etc/nginx/sites-enabled/example.com: server_name example.com www.example.com;
Grep Show File Name only
To stop the default grep output and print only filenames that contain matching patterns, you can use the options -l
(or --files-with-matches
).
For example to search all files ending in .conf
in the current working directory and prints only filenames containing string type example.com
:
grep -l example.com *.conf
The output will look like this:
tmux.conf haproxy.conf
Cucumber -l
Usually used with recursive options or -R
:
grep -Rl example.com /tmp
Grep is not case sensitive.
By default, the grep command is case sensitive which means uppercase and lowercase letters are treated as different.
To ignore the status when searching, use the options -i
(or --ignore-case
).
For example, when searching for the word Singa
Without any options, the following command will not return any output, even if there is a matching line.
grep Singa /usr/share/words
But if you do a case sensitive search using options -i
then it will search for every word with an uppercase and lowercase match:
grep -i Singa /usr/share/words
Using the word ‘Lion’ will match ‘lion’, ‘Lion’, or any other combination of uppercase and lowercase letters for the string.
singa sInGa's siNGA
Complete the word Grep
When searching for words aku
grep will also print the line where the word is aku
Also included in larger words, such as akurasi
And theketakutan
for example.
grep aku /usr/share/words
aku akurasi baku daku ketakutan pelaku pengakuan saku
To return lines where the given string is whole words (enclosed by non-word characters), you can use this option -w
(or --word-regexp
).
Word characters include alphanumeric characters (a-z
And the A-Z
And the 0-9
) and underscores (_
). All other characters are considered as non-words.
If you run the same command as above including the -w option, the grep command will output only those lines containing the word aku
It was entered as a single word and separated from the other letters.
grep -w aku /usr/share/words
aku
Grep to display the font number
To indicate the number of rows containing a string that matches the pattern, use options -n
(or --line-number
). When this option is used, grep will print matches to standard output starting with the line number found.
For example to display lines from a file /etc/services
which contains the string bash
Starting with a matching line number, you can use the following command:
grep -n 10000 /etc/services
The output below shows us that a match was found in the row 10423
And the 10424
.
10423:ndmp 10000/tcp 10424:ndmp 10000/udp
Grep to display the corresponding amount
To print the number of lines that match the standard output, use the options -c
(or --count
).
In the example below, we will count how many accounts it has /usr/bin/zsh
as shells.
grep -c '/usr/bin/zsh' /etc/passwd
4
Grep multiple strings (pattern)
Grep to display two or more search styles that can be combined OR
or |
.
By default, Grep interprets patterns as basic regular expressions where they are similar to descriptive characters |
Lost its own meaning and backslashed versions ( /
) must be used.
In the example below we will search all the words fatal
And the error
And the critical
In the Nginx error log file:
grep 'fatal\|error\|critical' /var/log/nginx/error.log
If you use the regular expression option with -E
(or --extended-regexp
) then operator |
Must not survivedAs shown below:
grep -E 'fatal|error|critical' /var/log/nginx/error.log
Regular expression Grep
GNU Grep contains two sets of regular expression features, basic and extended. By default, Grep interprets the pattern as a basic regular expression, to switch to an extended regular expression, you need to use the option -E
.
When used in basic regular expression mode, all other characters except the initials are actually self-matching regular expressions. Here is a list of the most commonly used meta characters:
- Use the code
^
(caret) to match the expression at the beginning of the line. Here is an example of a string^banteng
It will only match this word at the beginning of the line.grep "^banteng" file.txt
- Use the code
$
(in dollars) to match the expression at the end of the line. In the following example, the stringanoa$
It will only match if the word occurs at the end of the line.grep "banteng$" file.txt
- Use the code
.
(dot) to match any one character. For example, to match anything starting withban
Then it consists of two characters and ends with a stringng
you can use the following pattern:grep "ban..ng" file.txt
- Uses
[ ]
to match any single character in parentheses. For example, find the line containingaccept
oraccent
you can use the following pattern:grep "acce[np]t" file.txt
- Uses [
^
] to match every single character inside parentheses. The following pattern will match any string combination containing (huruf_apapun_kecuali_l
) Bothcoca
And thecobalt
etc., but it will not match the lines containing the wordcola
And thegrep "co[^l]a" file.txt
To avoid the special meaning of the next character, use the symbol \
(Backslash).
Extended Regular Expression Grep
To interpret the pattern as an extended regular expression, use the options -E
(or --extended-regexp
). Extended regular expressions include all the basic descriptive characters, along with additional descriptive characters to create more complex and efficient search patterns. Here are some examples:
- Match and extract all email addresses from the specified file:
grep -E -o "\b[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" file.txt
- Match and extract all valid IP addresses from the given file:
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
Cucumber -o
Used to print matching strings only.
Grep font before the match
To print a specified number of lines before matching lines, use the options -B
(or --before-context
).
For example, to display the first 5 lines of context before matching lines, you can use the following command:
grep -B 5 root /etc/passwd
Grep font after the match
To print a specified number of lines after matching, use the options -A
(or --after-context
).
For example to display 5 lines of context after the matching line, you can use the following command
grep -A 5 root /etc/passwd
conclusion
In this tutorial, you learned how to use Grep to find patterns in files. Actually this is the basis of grep and there is a lot to learn about Grep on the man page Grep
.