Linux grep command with examples

In this article, we will see Linux/Unix/Mac grep command with examples.

grep stands for Globally Search a Regular Expression and Print. grep is a command line utility for searching text data for lines which matching a regular expression. It displays all lines that contain that pattern.

Linux grep command Syntax:

grep [OPTIONS] PATTERN [FILE...]

Linux grep command with examples

1. Create a text files with name r2school.txt.

cat > r2schools.txt R2schools is website for technology tutorials and solution. r2schools also maintains youtube channel for technology solutions. R2SCHOOLS.com is the website name. As of now r2schools mainly focused on databases and Linux articles.

2. Search for the word ‘r2schools’.

grep r2schools r2schools.txt

From the above output, red color highlighted are the matched occurrences.

3. Case insensitive search using grep: We use -i options with grep command to search a string in a given file.

grep -i r2schools r2schools.txt

Compare the examples 2 and 3, we have more matches than example two.

4. Find the all files that matches a string using grep:

grep -l "r2schools" *

5. Find more than one word using in a file:
To find more than one word, we use egrep command.

egrep "technology|solutions" r2schools.txt

6. Find in how many lines a word present.

grep "r2schools" r2schools.txt -c

7. Display the line numbers of each match using grep command.

grep "technology" r2schools.txt -n

8. How to find a user exists or not using grep command:

grep r2schools /etc/passwd

9. Search fixed pattern using fgrep.

fgrep R2schools r2schools.txt

10. Search words recursively from files & directories:

sudo grep -r 'enp0s3' /etc

11. Search process status with grep command:

ps -aef | grep postgres

12. Find multiple search with grep command:

grep -e "r2schools" -e "technology" r2schools.txt

13. Inverting the pattern match :We can display the lines that are not matched with the specified search sting pattern using the -v option.

grep -v -n "R2schools" r2schools.txt

Linux grep command options:

-c : This prints only a count of the lines that match a pattern -h : Display the matched lines, but do not display the filenames. -i : Ignores, case for matching -l : Displays list of a filenames only. -n : Display the matched lines and their line numbers. -v : This prints out all the lines that do not matches the pattern -e exp : Specifies expression with this option. Can use multiple times. -f file : Takes patterns from file, one per line. -E : Treats pattern as an extended regular expression (ERE) -w : Match whole word -o : Print only the matched parts of a matching line, with each such part on a separate output line. -A n : Prints searched line and nlines after the result. -B n : Prints searched line and n line before the result. -C n : Prints searched line and n lines after before the result.