Fri. Aug 14th, 2020

How to search for files in Linux using the grep command

6 min read

The grep command is one of the most powerful and commonly used commands in Linux systems. Grep can search one or more files to find rows that match the “given pattern” and write each matching row to standard output. If no file is specified, grep can also read the output of other commands as standard input.

In this post, I will show you how to use the grep command to search on Linux systems.

Grep command syntax

Before discussing how to use the grep command, let’s review the basic syntax:

grep [ OPTIONS ] PATTERN [ FILE …]

Items in square brackets are optional.

OPTIONS provides one or more options for grep to control its behavior
PATTERN search mode
FILE one or more input files (name)

Use grep to search for strings in a file

The most basic use of the grep command is to search for strings (text) in the file. For example, to view the lines containing ddos in the /etc/passwd file, you can use the following command:

grep ddos /etc/passwd

If the string to be searched packet containing spaces, you will need to use single quotes or double quotes enclose, for example:

grep "systemd" /etc/passwd

Grep reverse match

If you want to display rows that do not match the search pattern, you can use the -v or –invert-match parameters. For example, to see the line that does not contain nologin in the /etc/passwd file, you can use the following command:

grep -v nologin /etc/passwd

Grep searches for the output of another command

If you are not searching for a file, you can pass the output of other commands to grep as the “input” for its search. For example, to find a process running on a current www-data user in Linux, you can execute the following command:

ps -ef | grep www-data

Grep searches for the output of another command

You can also link multiple pipes in a command. As you can see from the output above, there is a line that also contains the grep process. If you don’t want to display the line, you can pass the output to another grep instance again, for example:

ps -ef | grep www-data | grep -v grep

Grep recursive search

To use the recursive search mode, add the -r or –recursive parameter. Adding this parameter will search all the files in the specified directory and will skip when you encounter the “symbolic link”. If you want to search for “symbolic links”, you need to use the -R or –dereference-recursive parameters.

In the following example, we will recursively search for all strings containing sysgeek.cn in the /etc directory :

grep -r ddos /etc

This command will output the line containing the string and display its file name in front.

View only file names

To disable grep’s default output and display only filenames that contain “matching patterns”, you can use the -l or –files-with-matches parameters. For example, to search for all files in the current directory that end with .conf and contain the sysgeek.cn string, you can do:

grep -l ddos *.conf

The -l parameter is usually used in conjunction with the recursive parameter -R, for example:

grep -Rl ddos /tmp

Configuring grep is not case sensitive

By default, grep is case-sensitive, meaning that uppercase and lowercase characters are treated differently. To ignore case when searching, you can use the -i or –ignore-case parameter.

Grep exact match

When gnu is searched with grep, the entire word is automatically matched, such as cygnus or magnum :

grep ddos grep.txt

If you want to match the search word characters exactly, you can add the -w or –word-regexp parameters. Word characters include letters, numbers (a-z, A-Z, and 0-9) and underscores ( _ ). All other characters are treated as non-word characters.

If you execute the above grep command with the -w parameter, only those rows where gnu is a separate word are returned:

grep -w ddos grep.txt

Configuring grep to display line numbers

To display the number of lines of text in which the search string is located, you can use the -n or –line-number parameter, and with this parameter, grep prints the match to standard output and prefixes it with the text line number.

For example, to view the number of lines in the /etc/services file 80, you can execute:

grep -n 80 /etc/services

You can see :

Count with grep

To count matching rows, you can use the -c or –count parameters. For example, to see the current number of accounts using ddos in Linux, you can use the following command:

grep -c '/usr/bin/ddos' /etc/passwd

Grep multiple strings (pattern)

The OR operator | can connect two or more search modes. But by default, grep interprets “pattern” as a basic regular expression, where “meta characters” such as | loses its special meaning, so it must be negated.

As in the example below, we can search for all fatal, error, and critical words in the nginx error log file :

grep 'fatal\|error\|critical' /var/log/nginx/error.loge>

However, if you add the extended regular expression parameter -E or –extended-regexp parameter, the operator | should not be negated as follows:

grep -E 'fatal|error|critical' /var/log/nginx/error.log

Grep regular expression

Grep has two basic expressions, “Basic” and “Extended”. By default, grep’s mode is interpreted as a basic regular expression. To switch to an extended regular expression, you need to add the -E parameter.

When working in Basic mode, all characters except the “meta character” match the original regular expression. The following is a list of the most commonly used “meta characters”:

  • ^ (insert symbol) is used to match the beginning, for example, ^kangaroo will match the line that starts with it:
    grep “^ddos” grep.txt
  • $ (dollar sign) is used to match the line tail, using kangaroo$ to match only when it appears at the end of a line:
    grep “ddos$” grep.txt
  • . (Period) to match any single character, for example, to match to kan beginning, middle two characters, then roo end of the following modes:
    grep “dd..os” grep.txt
  • [] (brackets) to match any single character in the brackets, for example, to match accept or accent, you can use the following pattern:
    grep “acce[np]t” grep.txt

To mask the special meaning of characters, use the \ backslash.

Grep extended the regular expression

Extended regular expressions include all basic metacharacters, as well as other extended metacharacters, to create more complex and powerful search patterns. E.g:

Match and extract all email addresses in a given file:

grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" grep.txt

Match and extract all IP addresses in a 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]?)’ grep.txt

The -o parameter is used to print only matching strings.

Print grep to match the last N lines of the line

To print the N lines after the matching line, use the -A or –after-context parameters. For example, to display matching lines and the last 5 lines, you can use the following command:

grep -A 5 root /etc/passwd

Print grep matching the first N lines of the line
To print the first N lines of the matching line, use the -B or –before-context parameters. For example, to display matching lines and the first 3 lines, you can use the following command:

grep -B 3 www-data /etc/passwd

If you want to know more, you can refer to the grep man page.