Grep command
Table of Contents
————————————oc}
- TOC
Introduction
The grep command is a powerful utility for searching for strings or patterns in text files. It stands for “global regular expression print” and is commonly used to search for specific patterns of text within a file or a set of files.
Here is the general syntax for the grep command:
grep [options] PATTERN [FILE...]
-
options: Optional flags that modify the behavior of thegrepcommand. Some common options include-ifor case-insensitive matching,-vfor inverting the match, and-rfor searching recursively in a directory. -
PATTERN: The pattern or string to be searched for. -
FILE...: The input file or files to be searched. If no file is specified,grepwill read from the standard input stream.
For example, the following command will search for the word “apple” in the file fruits.txt:
grep "apple" fruits.txt
Grep or, and and not
-
grep or condition using
\|grep 'pattern1\|pattern2' filename
-
Grep OR Using
-Egrep -E 'pattern1|pattern2' filename
-
Grep OR Using
egrepegrep 'pattern1|pattern2' filename
-
Grep OR Using grep
-egrep -e pattern1 -e pattern2 filename
-
Grep AND using -E
pattern1.*pattern2grep -E 'pattern1.*pattern2' filenamegrep -E 'pattern1.*pattern2|pattern2.*pattern1' filename
-
Grep AND using Multiple grep command
grep -E 'pattern1' filename | grep -E 'pattern2'
-
Grep NOT using grep -v (This will print each line that does not contain the pattern.)
grep -v 'pattern1' filename
-
Print only file names that does not contain pattern (
-L)grep -L 'pattern' filename
-
Include/Exclude a particular file format from grep search 1:
grep pattern -r --include=\*.{cpp,h} rootdirgrep pattern -r --exclude=\*.{cpp,h} rootdir- To exclude directory use:
--exclude-dir={abc,def}
Reference: http://www.thegeekstuff.com/2011/10/grep-or-and-not-operators
-
https://stackoverflow.com/a/221929/2302094 ↩
Enjoy Reading This Article?
Here are some more articles you might like to read next: