반응형

Grep의 사용방법에 대해서 알아보는 시간을 갖도록 하겠습니다.

 

grep은 리눅스/유닉스 환경에서 문자열을 파싱할 수 있는 명령어 입니다. 이것을 잘활용하면 많은 효과를 볼 수 있는데 이에 대해 알아보는 시간을 갖도록 하겠습니다.

 

기본 옵션

1. -n : 파일 안에서의 패턴에 발견된 라인 및 라인 번호

2. -v : 패턴이 발견되지 않은 라인을 출력

3. -i : 대소문자 무시 (ignore)

4. -l : 패턴이 들어 있는 파일 이름만 출력

5. -c : 패턴이 들어있는 라인 번호의 개수

 

<옵션 분석>

1. grep 

root@ubuntu:~# grep root /etc/group
root:x:0:

2. grep -v : 해당 패턴을 제외한 결과 행을 출력

root@ubuntu:~# grep -v root /etc/group
daemon:x:1:
bin:x:2:
sys:x:3:

 

3. grep -c : 해당 패턴이 들어간 행의 개수를 카운트하여 출력
root@ubuntu:~# grep -c root /etc/group
1

4. grep -l : 해당 패턴을 대상 파일에 존재하는지를 판단하고 존재한다면 대상 파일명을 출력

root@ubuntu:~# grep -l root /etc/group /etc/hosts /etc/passwd
/etc/group
/etc/passwd

5. grep -i :  대소문자를 구별하지 않고 패턴에 해당하는 문자가 포함된 행을 출력

root@ubuntu:/shell# grep -i boy sample.txt
I am a boy
Boy have a robot

<특수문자>

1. 사각괄호 ([ ]) : [ ] 안에 들어 있는 검색을 모두 수행한다.

2. 마침표 ( . ) : 한 문자를 대신한다. 대신한 문자는 모든 문자로 간주 검색을 한다.

3. 괄호안의 대시 ( [ - ] ) :  - 괄호 안의 무자 잡합의 문자 범위를 지정한다.

4. 탈자기호 ( [ ^ ] ) : ^ 특정 조건에 속하지 않은 문자열을 출력한다.

5. 별표 ( * ) : * 지정한 문자열이 0, 1 , 수 차례 반복된다는 의미

6. 행시작(^)끝($) : ^ 괄호 밖의 탈자기호는 행 시작부만 검색한다는 의미이고 $는 지정한 문자열로 끝나는 행만 검색

 

<특수문자 활용>

1. 사각괄호 ([ ]) : [ ]안의 안의 문자집합을 모두 검색해 출력한다.

root@ubuntu:/shell# grep [bg] sample.txt
I am a boy
Boy have a robot
Robot is a blue
You are a girl
root@ubuntu:/shell# grep [BG] sample.txt
Boy have a robot
Girl have a doll

 

2. - 의 사용

root@ubuntu:/shell# grep [a-z]oy sample.txt
I am a boy
root@ubuntu:/shell# grep [a-z]irl sample.txt
You are a girl
root@ubuntu:/shell# grep [A-Z]irl sample.txt
Girl have a doll
root@ubuntu:/shell# grep [A-Z]oy sample.txt
Boy have a robot
root@ubuntu:/shell# grep [A-Za-z]oy sample.txt
I am a boy
Boy have a robot

 

3. . 의 사용 : . 은 한 문자를 대신하여 그에 속한 모든 문자(공백 포함)를 출력

root@ubuntu:/shell# grep b.y sample.txt
I am a boy
root@ubuntu:/shell# grep b.. sample.txt
I am a boy
Boy have a robot
Robot is a blue
root@ubuntu:/shell# grep b... sample.txt
Robot is a blue
root@ubuntu:/shell# grep b.... sample.txt
Robot is a blue
root@ubuntu:/shell# grep b.... sample.txt

4. [ ] 안의 ^의 사용 : 이것은 혼자 쓰이는 ^와는 다르다. ^은 포함하지 않는 문자열을 검색

root@ubuntu:/shell# grep b[^o]y sample.txt
root@ubuntu:/shell# grep b[^a]y sample.txt
I am a boy
root@ubuntu:/shell# grep [^b]oy sample.txt
Boy have a robot

 

5. *의 사용 : *은 반복을 나타내는 연산 중 하나이다. 파일 검색과는 조금 다르니 혼단하지 말았으면 합니다. 정규연산식에서 *은 지정한 문자열이 반복되는 반복되지 않든 모두 검색하라는 것이다.

root@ubuntu:/shell# grep b*oy sample.txt
I am a boy
Boy have a robot
root@ubuntu:/shell# grep bo*y sample.txt
I am a boy

6.  [ ] 밖의 ^사용 : ^는 지정한 검색 문자열로 시작하는 행만을 검색하여 반환합니다.

root@ubuntu:/shell# grep ^I sample.txt
I am a boy
root@ubuntu:/shell# grep ^B sample.txt
Boy have a robot
root@ubuntu:/shell# grep ^I sample.txt
I am a boy

 

7. $의 사용 : $는 지정한 검색 문자열로 끝나는 행만을 검색하여 반환

root@ubuntu:/shell# grep boy$ sample.txt
I am a boy
root@ubuntu:/shell# grep girl$ sample.txt
You are a girl


 

 

반응형

+ Recent posts