20 Useful Grep Command Examples in Linux

Grep is a command-line utility widely used in Linux/Unix that uses in searching data sets of specific files for lines that match a regular expression of plain texts. Grep stands for Global Regular Expression Print. It was originally named by Ken Thompson who was also the original author. He named it so because in ed the command g/re/p has the same effect as grep. In this guide we will cover 20 useful grep command examples.

Syntax to use:

$ grep [option] [pattern] [files]

Option refers to the extra parameters to invoke or access the inbuilt feature. You can use the following command to check info on all options.

$ grep --help

The pattern implies plain text or regular expression (shortened as regex) to search matching sets of data. Regex is a sequence of characters that specifies a search pattern.

Let’s dive into examples of grep command.

1) Search text from the file.

$ grep “Search Text” filename

Create a new text file that contains some text. Then, we simply need to use the grep command then specify the regex pattern or word we want to search. We can search sentences also if we want. Lastly, we need to provide a filename. If our working directory and file directory are different we need to specify the file path with filename. The output will be the row containing search text or word. Example is shown below:

$ grep nobody /etc/passwd
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
$

2)  Grep case insensitive search

$ grep -i “text” filename

By default grep command output our searched text case-sensitively. Suppose we have a paragraph that contains the same words with different cases. In such a case we can use the -i option to get outputs case-insensitively.

$ grep -i 'pKumar' /etc/group
adm:x:4:syslog,pkumar
sudo:x:27:pkumar
pkumar:x:1000:
docker:x:998:pkumar
$

3) Search exact words only

$ grep -w “text” filename

In the above example, the grep command shows the output based on the sub-string. What if we want to search by words only not by sub-string. For that, we use the hyphen w (-w) option to perform such a search.

$ grep -w 'DOCKER' /etc/group
$ grep -w 'docker' /etc/group
docker:x:998:pkumar
$

4) Search words recursively from files & directories

$ grep -r “text” <directory-or-file-path>

Let’s assume we have files in directories and their sub-directories also have some files, we want to search words or sentences from all those files to do so we need to add hyphen r (-r). It informs the command to check all files recursively from all directories and sub-directories of the given path.

$ sudo grep -r 'enp0s3' /etc
/etc/ufw/after.rules:-A DOCKER-USER -i enp0s3 -j ufw-user-input
/etc/ufw/after.rules:-A DOCKER-USER -i enp0s3-j DROP
$

5) Searching the line or word along with the line numbers

$ grep -n “text” filename

Searching words or sentences is easier using the grep command but it will be much easier if we could also view the line numbers where the search word is located. We can do so in the grep command by adding the hyphen n (-n) option. Passing this option will show results with the line number which help us to locate the search texts in files.

$ grep -n 'docker' /etc/group
74:docker:x:998:pkumar
$

6) Listing files and directories using grep

$ ls -a | grep [filename or directory name]

Listing files and directories using the ls command will be easier if there are fewer files or dir.

For many files and directories, we can filter out them using grep with pipe ( | ) which helps us to locate the file faster. In Linux pipe command lets you send the output of one command to another.

[email protected]:~$ ls -l /etc | grep sudo
-r--r----- 1 root root 755 Feb 3 2020 sudoers
drwxr-xr-x 2 root root 4096 Feb 12 10:17 sudoers.d
[email protected]:~$

7) cat using grep command

$ cat filename1 filename2 filename3 | grep -i ‘search-text’

Or

$ cat filename2 >>filename1

$ cat filename1 | grep -i ‘search-text’

Cat command allows us to view a single file, multiple files, concatenate files. Searching specific phrases or from multiple files might be quite complicated. In the second example, the cat command appends all the text from filename2 to filename1 at the endpoint of filename1 text. Later grep command can filter out the required text.

8) Finding specific dot deb package listing

$ dpkg -l | grep -i nginx

search-debian-package-grep-command

Using Debian base Linux will provide many preinstall dot deb packages, dpkg command handle all the dot deb packages. dpkg -l will do the listing of all the packages available in the system. Use grep with pip | to filter out the specific packages and the –i option will ignore-case in the filtering process.

9) Search Process Status (ps)

$ ps aux | grep -w tomcat

This command is the most common and frequently used Linux command that provides more and detailed process info of the system. In the above example, aux refers to options of ps command where p option prints all the running processes in the system, u option prints user of the process and lastly x option prints the processes that have not been executed from the terminal. Piping grep command to filter out tomcat and other processes.

10 ) Search Socket Statistics (ss) using grep

$ ss -lt | grep -w 8080

The ss (socket statistics) command provides a lot of information by displaying details on socket activity and port listening. -lt prints the display listening sockets and TCP sockets respectively. Lastly, filter out the tomcat default port using grep.

11 ) Search inside compressed files

$ gzip test.txt
$ zgrep -i 'search-text' test.txt.gz

The zgrep command is used to invoke the grep command inside the compressed file and search out expressions from a given compressed file. This command print out the search value without extracting the compressed files. All the options that apply to the grep command also apply to the zgrep command.

12) Search files including particular text

$ grep -l "pattern or text" *.txt

Suppose we have a bunch of text files and we want to view all the filename that contains specific text or sentences. Pass the hyphen -l option to the grep command and specify all the filename using the pattern or name do the work. For the current context, we have included all the files with the dot txt extension.

13) Finding exceptions in error logs

$ grep -in "exception" logs/catalina.out
or
$ cat logs/catalina.out | grep -in "exception"

One of the most complicated things on any server is to analyze the server log and resolve any exceptions. Simply reading logs using the filter is a more efficient and easy way to deal with exceptions. In the above command, adding the -in option to grep command will show the output of tomcat logs with case insensitive filter, and the line number of exceptions has occurred.

14 ) Count the Number of line matches pattern

$ grep -ic “this” file1.txt

If you ever get wonder about the number of lines that match the patterns, passing the -c option to the command do the work for you. Example is shown below:

$ grep -ic pkumar /etc/group
4
$

15) Search command from history command’s output

$ history | grep -i systemctl

The history command is the most used in Linux/Unix. It helps in monitoring the executed command by users. Piping grep command with history may filter-out the specific command that had been executed so, it will much easier to trace out the user executed command.

16) Escape Special Characters(\)

$ grep " \ $20 " filename.txt

Let’s consider you have some paragraph on the annual budget and it contains special character like $, %, etc. In Linux/Unix special character has its special meaning like ‘*’ denoted as all and so on which may be an obstacle in searching. In such a case, we can escape any other special characters using a backslash (\).

Note: In the grep command, meta-characters lose their meaning and are treated as normal characters of the string and need to use a backslash to treat them as special characters.

17)  Grep with Multiple Pattern

$ grep -e “test” -e “is” fiilename.txt

Ever wonder if we could search multiple words or patterns at a time. The grep utility enables users to search for lines with multiple patterns at the same time. Simply passing hyphen e (-e) before every pattern as shown in the above example. It will print all the lines matching the patterns.

$ grep -e sudo -e adm /etc/group
adm:x:4:syslog,pkumar
sudo:x:27:pkumar
lpadmin:x:120:
$

18 ) Extended Global Regular Expressions Print (egrep)

$ egrep -i "m{2}" file.txt
Or
$ grep -Ei "m{2}" file.txt

The egrep is an extended version of grep that is faster and efficient as compare to grep. Passing -E option to grep command invoke egrep command. It treats meta-characters as it is and doesn’t lose their meaning of special characters just like in grep.

Note: In egrep escaping special characters will be treated as characters.

19 ) Fixed Global Regular Expressions Print (fgrep)

$ fgrep -i "search-text" filename.txt
or
$ grep -F "search-text" filename.txt

The fgrep is also another version of grep for searching string only. It doesn’t understand special characters or meta-characters and treated them as string character even if escaped or not escaped. It can be extended by passing the -F option in the grep command.

20)  Select Matches at Beginning (^) and Ending ($)

$ grep -i "^t" filename.txt
$ grep -i "t$" filename.txt

In the above example, we use special characters ^ and $ where ^ denotes started with and $ denotes ended with. The first command will print all the lines that start with ‘t’ and the second command will print all the line that ends with ‘t’.

Conclusion

In our daily routine of software development or any other profession that involves continuous use of Linux have to go through large swaths of text either they may be any logs on the server or user activity. Grep may filter out a specific line of text you are searching for, which decreases your working complexity and time. If you are familiar with regular expression it might be more effective in filtering.

These are some common examples of grep command that I find most useful in our day-to-day jobs that add more flexibility in reviewing any documents or file.

Also Read : 9 Quick ‘mv’ Command Practical Examples in Linux

Leave a Reply

Your email address will not be published. Required fields are marked *

2 × 4 =