How to Use grep Command on Linux – Guide

Grep is an essential command for Linux and Unix. It is used to find text and strings in a specific file. In others words, the grep command searches the specified file for lines that match the strings or words.

A line in a text file is a sequence of characters until a line break is inserted. The output of grep commands can contain entire paragraphs unless the search options are refined. The grep filter looks for a specific character pattern in a file and displays all lines that contain that pattern. The pattern searched in the file is called a regular expression (grep stands for global regular expression and expression search). ..

Grep Command Syntax:

Grep is a versatile command line tool for searching through files. It can be used to search for specific strings, or to compare two files side-by-side. You can also use grep to search through a file’s contents using wildcards.

grep -e ‘^.*$’ -f /etc/passwd

Usage examples of ‘grep’

grep foo /file/name

Searching for “foo” in the file “/file/name” will return a list of all matches on separate lines. ..

grep -i “foo” /file/name

The -i option can be useful when searching for a word that has multiple cases, such as “Foo Foo” or “foo bar”. ..

grep ‘error 123’ /file/name

Grep is a versatile tool that can search for specific words or strings in a file. By enclosing the string sequence that forms the pattern in quotes, grep can find all occurrences of the word ‘error’ in the file /file/name.

grep -r “192.168.1.5” /etc/

The grep search area can be expanded further by using its -r option to search an entire directory tree. The above example searches all files in the /etc/ directory and all its subdirectories (including its subdirectories) for the string ‘192.168.1.5’ ..

grep -w “foo” /file/name

When you search for foo, grep will match any word that contains a match in the text it is searching. You can force grep to only select those lines that contain a match using the -w option.

egrep -w ‘word1|word2’ /file/name

Search and display “file” and “name” in the same field.

grep -c test /file/name

The -c option causes grep to only report the number of times the pattern was matched for each file and not display the actual lines.

grep –context=6 error /file/name.txt

The grep –context option can be helpful when looking for specific lines around a matching line. In the example above, the –context option is used to print the 6 lines before and after a corresponding line with the word “error” in /file/name.txt ..

Final note

Grep is a powerful command line tool that can be used to search through files and directories. This guide will show you how to use grep on Linux. ..