Tutorials  /  Linux Basics

Grep Command in Linux/UNIX

Ccentron Redaktion · November 2024 ·10 min read ·Linux Basics, Tutorial

What is Grep

Grep, short for “global regular expression print”, is a command used for searching and matching text patterns in files contained in the regular expressions. Furthermore, the command comes pre-installed in every Linux distribution. In this guide, we will look at the most common grep command usages, along with popular use cases.

VM

Try it yourself: cloud servers from €3.12/month

ccloud³ VMs from German data centers – deployed in seconds, billed by the hour, with a €200 starting credit for new accounts. Launch a server →

Grep Command in Linux

Grep command can be used to find or search a regular expression or a string in a text file. To demonstrate this, let’s create a text file welcome.txt and add some content as shown.

Code
Welcome to Linux!
Linux is a free and opensource Operating system that is mostly used by
developers and in production servers for hosting crucial components such as web
and database servers. Linux has also made a name for itself in PCs.
Beginners looking to experiment with Linux can get started with friendlier linux
distributions such as Ubuntu, Mint, Fedora and Elementary OS.

Great! Now we are ready to perform a few grep commands and manipulate the output to get the desired results. To search for a string in a file, run the command below:

Code
grep "string" file name

OR

$ filename grep "string"

```bash

**Example**:

```bash

$ grep "Linux" welcome.txt

Output:Grep text example

Grep Command Usage

As you can see, grep has not only searched and matched the string “Linux” but has also printed the lines in which the string appears. If the file is located in a different file path, be sure to specify the file path as shown below:

Console
$ grep "string" /path/to/file
```bash

## Colorizing Grep results using the --color option

If you are working on a system that doesn't display the search string or pattern in a different color from the rest of the text, use the `--color` to make your results stand out. Example

```bash
$ grep --color "free and opensource" welcome.txt

Output:Grep color

Searching for a String Recursively in All Directories

If you wish to search for a string in your current directory and all other subdirectories, search using the -r flag as shown:

Code
grep -r "string-name" *

For example:

Code
grep -r "linux" *

Output:Grep recursive

Ignoring Case Sensitivity

In the above example, our search results gave us what we wanted because the string “Linux” was specified in Uppercase and also exists in the file in Uppercase. Now let’s try and search for the string in lowercase.

Code
grep "linux" file name

Nothing from the output, right? This is because grepping could not find and match the string “linux” since the first letter is Lowercase. To ignore case sensitivity, use the -i flag and execute the command below:

Code
grep -i "linux" welcome.txt

Output:Grep ignore case sensitivity

Awesome isn’t it? The -i is normally used to display strings regardless of their case sensitivity.

Count the Lines Where Strings Are Matched with -c Option

To count the total number of lines where the string pattern appears or resides, execute the command below:

Code
grep -c "Linux" welcome.txt

Output:Grep count number of lines

Using Grep to Invert Output

To invert the Grep output, use the -v flag. The -v option instructs grep to print all lines that do not contain or match the expression. The –v option tells grep to invert its output, meaning that instead of printing matching lines, do the opposite and print all of the lines that don’t match the expression. Going back to our file, let us display the line numbers as shown. Hit ESC on Vim editor, type a full colon followed by:

Code
set nu

Next, press Enter OutputLine number in vim

Now, to display the lines that don’t contain the string “Linux,” run:

Code
grep -v "Linux" welcome.txt

Output:Grep invert output

As you can see, grep has displayed the lines that do not contain the search pattern.

Number the Lines That Contain the Search Pattern with -n Option

To number the lines where the string pattern is matched, use the -n option as shown:

Code
grep -n "Linux" welcome.txt

Output:Grep line number where string appears

Search for Exact Matching Word Using the -w Option

Passing the -w flag will search for the line containing the exact matching word as shown:

Code
grep -w "opensource" welcome.txt

Output:Grep search exact matching pattern

However, if you try:

Code
grep -w "open" welcome.txt

NO results will be returned because we are not searching for a pattern but an exact word!

Using Pipes with Grep

The grep command can be used together with pipes for getting distinct output. For example, if you want to know if a certain package is installed in an Ubuntu system, execute:

Code
dpkg -L | grep "package-name"

For example, to find out if OpenSSH has been installed in your system, pipe the dpkg -l command to grep as shown:

Code
dpkg -L | grep -i "openssh"

Output:Grep package name

Displaying Number of Lines Before or After a Search Pattern Using Pipes

You can use the -A or -B to display the number of lines that either precede or come after the search string. The -A flag denotes the lines that come after the search string and -B prints the output that appears before the search string. For example:

Code
ifconfig | grep -A 4 ens3

This command displays the line containing the string plus 4 lines of text after the ens string in the ifconfig command.

Output:Grep lines after search string

Conversely, in the example below, the use of the -B flag will display the line containing the search string plus 3 lines of text before the ether string in the ifconfig command. Output:

Code
ifconfig | grep -B 4 ether
Grep lines before search string

Using grep with REGEX - regular expressions

The term REGEX is an acronym for REGular EXpression. A REGEX is a sequence of characters that is used to match a pattern. Below are a few examples:

Code
^      Matches characters at the beginning of a line
$      Matches characters at the end of a line
"."    Matches any character
[a-z]  Matches any characters between A and Z
[^ ..] Matches anything apart from what is contained in the brackets

Example

To print lines beginning with a certain character, the syntax is;

Example

To print lines beginning with a certain character, the syntax is;

Code
grep ^character file_name

For instance, to display the lines that begin with the letter “d” in our welcome.txt file, we would execute

Code
grep ^d welcome.txt

Output:Regex beginning of line

To display lines that end with the letter ‘x’ run

Code
grep x$ welcome.txt

Output:Regex end of line

Getting help with more Grep options

If you need to learn more on Grep command usage, run the command below to get a sneak preview of other flags or options that you may use together with the command.

Code
grep --help

Sample Output:Grep help

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Linux Basics
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren