Deep Dive into the Linux ‘grep’ Command and Its Parameters

Vitalii Shloda
2 min readJul 17, 2023

--

The ‘grep’ command is one of the most frequently used and powerful commands in the Linux operating system. Short for ‘Global Regular Expression Print’, ‘grep’ is mainly used to search text or search the given file for lines containing a match to the given strings or words. It can search through one or many files, and can even search through the output of other commands. In this article, we will explore the ‘grep’ command in detail, focusing on its various parameters and how they can be utilized.

Basic ‘grep’

The basic syntax of the ‘grep’ command is as follows:

grep 'pattern' file

For example:

grep 'hello' file.txt

This command will search for the string ‘hello’ in the file ‘file.txt’ and print all the lines containing this string.

-i

The ‘-i’ option makes the ‘grep’ command case-insensitive.

grep -i 'hello' file.txt

This command will find ‘hello’, ‘Hello’, ‘HELLO’, and any other combination of upper and lower case letters.

-v

The ‘-v’ option inverts the search, printing only the lines that do not contain the target pattern.

grep -v 'hello' file.txt

This command prints all the lines from ‘file.txt’ that do not contain the word ‘hello’.

-r or -R

The ‘-r’ or ‘-R’ option makes the ‘grep’ command search for the target pattern recursively in the directory specified and all of its subdirectories.

grep -r 'hello' /home/user/

This command will search for ‘hello’ in all files in the ‘/home/user/’ directory and its subdirectories.

-l

The ‘-l’ option makes ‘grep’ print only the names of files with matching lines, separated by newlines.

grep -l 'hello' *

This command prints the names of all files in the current directory that contain the word ‘hello’.

-w

The ‘-w’ option instructs ‘grep’ to search for the exact word and to ignore partial matches.

grep -w 'hello' file.txt

This command will only match lines containing ‘hello’ as a complete word.

-c

The ‘-c’ option makes ‘grep’ print only a count of matching lines for each input file.

grep -c 'hello' file.txt

This command will return the number of lines that contain the word ‘hello’ in ‘file.txt’.

-n

The ‘-n’ option adds line numbers to ‘grep’ output, showing where in the file the matching strings are located.

grep -n 'hello' file.txt

This command prints the matched lines along with their line numbers in ‘file.txt’.

The ‘grep’ command and its options offer powerful search capabilities that, when fully utilized, can speed up your command-line work immensely. It’s important to practice these commands regularly to become more comfortable with them and to learn how to combine them effectively. The next time you need to find a string or pattern in a text, remember these ‘grep’ parameters to make your search more efficient.

--

--

Vitalii Shloda
Vitalii Shloda

Written by Vitalii Shloda

Software Engineer. I write about backend, data and other amazing stuff

No responses yet