grep

What is grep?

grep is a command-line utility for searching plain-text data sets for lines that match a regular expression. Its name comes from the ed command g/re/p (globally search for a regular expression and print matching lines), which has the same effect. grep was originally developed for the Unix operating system, but later available for all Unix-like systems and some others such as OS-9.

long story short : it filters a file on the conditions that you give the grep command

How to use grep

Be sure to understand the pipe command first

# syntax : 
grep <OPTIONS> <FILTER> <FILE>

##### filter on specific conditions
cat /etc/passwd | grep root # filter on the word root, case sensitive
cat /etc/passwd | grep -i root # filter on the word root, not case sensitive

cat /etc/passwd | grep -i root --color # filter on the word root, not case sensitive and provide the matches with a color
cat /etc/passwd | grep -i -e root -e mail --color # filter on the word root and the word email, provide both with a color when found

cat /etc/passwd | grep -i -e root -e mail --color -w # filter ONLY on the word "root" and "mail"(no other alphabetical characters can be behind or infront of the word)
cat /etc/passwd | grep -i -x root:x:0:0:root:/root:/bin/bash --color # filter on the entire line. If it matches, it will return, else it will not

cat /etc/passwd | grep -i -e root -e mail --color -w -m 1 # filter on the first match of the file /etc/passwd with the name "root" and "mail"
cat /etc/passwd | grep -G "^r[a-z]" --color # search for everything that starts with the letter r (Case sensitive) in order to know more about regex, checkout the following link : https://www.digitalocean.com/community/tutorials/using-grep-regular-expressions-to-search-for-text-patterns-in-linux 

References

Last updated