Linux Command: grep

Published on December 2, 2021 at 7:56 am by LEW

Introduction

The grep utility is used to search for lines that match a plain text pattern. The name is an acronym for its function, Globally search for a Regular Expression and Print matching lines. The grep command is available on most Unix/Linux operating systems.

What grep does is search through a file and output all lines with text that matches the search pattern. It can be used as a stand alone command, but is probably more used in pipes between commands.

Syntax and Function

The syntax of the grep command is:

grep [options] patterns [files]

Grep has a large number of options, and while a few will be listed in the post, please visit the man page for your OS to get a complete list.

The patterns is the text that is to be searched for.

The files are the files to search in. The files are not used when grep takes its input form a pipe.

Examples

A basic use if grep is to search log files for specific alerts, errors, or other information. For example to search the /var/log/syslog for any errors, you would use the following grep command.

grep error var/log/syslog

If you were looking for a firmware issue you might want to search the results of the dmesg command. The dmesg command will output pages of information, which can be daunting to look through. This process is simplified with the following use of grep in a pipe.

dmesg | grep firmware

Another common use of grep in a pipe is to find specific files in directory listings from the ls command. This time we will use a wild card to match any jpg picture file.

ls /home/user1 | grep *.jpg

LS pipes the results of a list of user1 home directory to grep which in turn searches for any files with a .jpg extension.

Options

A few of the more common options for grep are listed below.

Conclusion

In this post we have taken a short look art the grep command. It is very powerful and one I use fairly often when working in the terminal. It is well worth your time to learn how to use it.

Add New Comment

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