2010. 12. 3. 09:11

Ubuntu/Linux의 grep으로 text 검색하기

grep 명령은 file에서 보다 정교한 문장을 찾는데 유용하게 사용됩니다. 사실, grep이라는 용어는 computer 전문용어로 사용되기도 합니다. 물론, 이제는 google 단어도 인기있는 단어이지요. 다음은 grep 명령의 예를 보여줍니다.
  • $ grep greenfish myfile.txt
    greenfish를 포함하고 있는 줄을 보여준다.
  • $ grep 404 /var/log/httpd/access_log
    404를 포함하고 있는 줄을 보여준다.
  • $ ps auwx | grep init
    ps output에서 init 줄을 보여준다.
  • $ ps auwx | grep "\[*\]"
    괄호가 쳐진 명령을 보여준다.
  • $ dmesg | grep "[ ]ata\|^ata"
    ata kernel device 정보를 보여준다.

위 예의 각각의 결과는 아래와 같습니다.

$ grep greenfish myfile.txt
greenfish is myid
$ ps auwx | grep init
root         1  0.0  0.2   2664  1516 ?        Ss   15:30   0:01 /sbin/init
1000      7925  0.0  0.1   3324   876 pts/0    S+   18:58   0:00 grep --color=auto init
$
ps auwx | grep "\[*\]"
root         2  0.0  0.0      0     0 ?        S    15:30   0:00 [kthreadd]
root         3  0.0  0.0      0     0 ?        S    15:30   0:00 [migration/0]
...
$ dmesg | grep "[ ]ata\|^ata"
[    1.681006] ata_piix 0000:00:07.1: version 2.13
[    1.688371] scsi0 : ata_piix
...



위의 명령들은 특별한 경우 사용되는데, grep의 좋은 예가 됩니다. access_log에서 404를 찾는 것은 page not found 로그를 찾는 것입니다. [ ] 명령을 찾는 것은 ps 명령 자체가 제공하지 않은 option을 보기위해 사용한 경우입니다. 마지막 예는 ata device 정보를 표시합니다.

grep 명령은 역시 동시에 여러개의 전체 혹은 일부 file을 찾는데 사용됩니다. 아래의 명령은 /etc/httpd/conf와 /etc/httpd/conf.d directory에 있는 파일에서 VirtualHost 문장을 재귀적으로 찾도록 합니다.

  • $ grep -R VirtualHost /etc/httpd/conf*

물론 시스템에 따라 /etc/httpd directory에 conf 파일이 없을 수 도 있습니다. 위 예를 다른 유사건으로 응용하여 사용하십시요.

grep 명령에 line 번호(-n)를 추가하여 발견된 단어가 포함된 line 번호를 표시하도록 합니다.

  • $ grep -Rn VirtualHost /etc/httpd/conf*

color로 표시하고 싶으면 아래와 --color을 사용하기도 합니다.

기본값으로 여러 파일을 검색할 때, file name이 검색의 결과에 각각 표시됩니다. -h 옵션을 사용하여 이를 비활성화 할 수 있습니다. 다음은 auth.log에 sshd를 찾는 예를 보여줍니다.

$ grep -h sshd /var/log/*
Nov 16 17:23:49 ubuntu sshd[6976]: pam_unix(sshd:session): session closed for user greenfish
Nov 16 17:24:02 ubuntu sshd[7210]: Accepted password for greenfish from 172.16.121.59 port 3350 ssh2
...
$ grep sshd /var/log/*
...
/var/log/auth.log.1:Oct 18 17:50:30 ubuntu sshd[1739]: pam_unix(sshd:session): session opened for user greenfish by (uid=0)
/var/log/auth.log.1:Oct 18 17:51:30 ubuntu sshd[1825]: Accepted password for greenfish from 172.16.121.59 port 1153 ssh2
...

그리고 -i 옵션을 이용하여 대소문자 구별을 하지 않도록 할 수 있습니다.

  • $ grep -i selinux /var/log/messages

그리고 -l 옵션을 사용하여 file 이름만 표시하도록 할 수 있습니다.

# grep -Rl sshd /var/log/*
/var/log/auth.log
/var/log/auth.log.1
#

-v 옵션을 사용하면 match 되지 않은 line을 보여줍니다.

  • $ grep -v " 200 " /var/log/httpd/access_log*
    " 200 "이 포함되지 않은 줄을 표시한다.

참고로, ps의 output을 grep할 때 grep process를 표시하지 않게 하기 위한 trick은 다음과 같습니다.

  • ps auwx | grep "[i]nit"