[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 matching a pattern
# Basic Usage
$ grep [OPTIONS] PATTERN [FILE...]
$ grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]

# Example 1
$ grep pattern filename

# 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
  • 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 contain pattern.


(Method) Use -v option

# Example 1
$ cat test.txt | grep -v pattern

# Example 2
$ cat test.txt | grep -v pattern1 | grep -v pattern2


Reference

[Docker] 도커(Docker) 이미지 이름과 태그 목록 가져오기

> 도커(Docker) 이미지 이름과 태그 목록을 awk과 tail 명령어를 이용해 가져오는 방법을 알아보자## 환경- Linux 기반 시스템- Bash shell(/bin/bash)- Docker- awk, tail 명령어## 도커(Docker...… Continue reading