[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

[Linux] 쉘 스크립트에서 멀티프로세스(혹은 스레드) 기능 사용하기

> 백그라운드로 명령어를 실행해서 병렬적으로 실행되는 멀티 프로세스 환경을 만들어보자.## 환경- Linux 기반 시스템- Bash shell(/bin/bash)## 멀티프로세스? 병렬처리? 멀티스레드? 백그라운드 프로세스?- 여기서 진행할 방식...… Continue reading