[Linux](EN) AND, OR, NOT condition usage in grep command
Use AND, OR, NOT condition in grep command
Environment and Prerequisite
- Linux base system
- Bash shell(/bin/bash)
What is grep?
grep
grep
: Print lines that match patterns.
# Basic Usage
$ grep [OPTIONS] PATTERN [FILE...]
$ grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
- File name and pattern usage
# Example 1
$ grep pattern filename
- Pipe and pattern usage
# Example 2
$ cat << EOF | grep example
> test
> example
> example1
> example+test
> this
> is
> EOF
example
example1
example+test
AND Condition Usage
Purpose
- Print lines which contain all patterns.
(Method1) Use multiple grep
- Use multiple grep with pipe
$ cat test.txt | grep pattern1 | grep pattern2
(Method2) Use -E option
- Use
-E
option. - You can use Regular Expression in grep with
-E
option. Like below, it prints lines which contain pattern1 and pattern2. However order will be pattern1 -> pattern2.
$ grep -E grep "pattern1.*pattern2"
- Following example will print all lines which contain both pattern1 and patter2 without any order.
$ grep -E grep "pattern1.*pattern2|pattern2.*pattern1"
OR Condition Usage
Purpose
- Print lines which contain at least one pattern.
(Method1) Use -e option
$ cat test.txt | grep -e pattern1 -e pattern2
(Method2) Use -E option
$ cat test.txt | grep -E "pattern1|pattern2"
NOT Condition Usage
Purpose
- Print lines which does not match pattern.
(Method) Use -v option
# Example 1
$ cat test.txt | grep -v pattern
# Example 2
$ cat test.txt | grep -v pattern1 | grep -v pattern2