grep [検索文字列] [検索対象]
が基本ですが、検索対象はファイル内の文字列であったりファイル名であったりします。
ファイルの中の文字列を検索する
1 2 3 4 | ##特定のファイル内から一致する行 [root@centos log] # grep ntpd messages* messages.1:Jun 3 18:14:17 localhost ntpd[2210]: Listening on interface wildcard, 0.0.0.0 #123 Disabled messages.1:Jun 3 18:14:17 localhost ntpd[2210]: Listening on interface wildcard, :: #123 Disabled |
1 2 3 4 5 6 | ##カレントディレクトリを対象とする [root@centos] # grep test * ##もしくは [root@centos] # grep test ./* test1:test1 test2:test2 |
1 2 3 4 5 6 7 8 | ##カレント配下のディレクトリを対象とする ##-Rオプションを使用して、指定したディレクトリを再帰的に検索します。 [root@centos] # grep -R test . ##もしくは [root@centos] # grep -R test ./* . /test1 :test1 . /dir1/test3 :test3 . /test2 :test2 |
1 2 3 | ##特定のファイルは検索対象外にする(ログファイル等) ## | grep -v "*log*" はダブルクォーテーションで囲む [root@centos] # grep -R test . | grep -v "*log*" |
ファイル名を検索する
1 2 3 4 5 | ##lsでファイル名を表示させてそれをgrepします。 ##カレントディレクトリを対象とすう [root@centos] # ls | grep test test1 test2 |
1 2 3 4 5 6 | ##カレント配下のディレクトリを対象とする ##findでファイル名を検索し、それをgrepします。 [root@centos] # find ./ -type f | grep test . /test1 . /dir1/test3 . /test2 |
ディレクトリ名を検索する
1 2 3 4 5 6 | ##findでディレクトリ名を検索し、それをgrepします。 ##カレント配下のディレクトリを対象とする [root@centos] # find ./ -type d | grep dir . /dir1 . /dir1/dir2 . /dir1/dir2/dir3 |
よく使用するオプション
1 2 3 4 5 6 7 | ##-i ・・・大文字小文字を区別しない ##-iオプションがなければ大文字小文字は区別されます [root@centos] # grep TEST ./* ##-iオプションがあれば大文字小文字は区別されません [root@centos] # grep -i TEST ./* . /test1 :test1 . /test2 :test2 |
1 2 3 4 | ##-v ・・・パターンにマッチしなかった行を抜き出して表示する [root@centos] # grep -v TEST ./* . /test1 :test1 . /test2 :test2 |
1 2 3 4 5 6 | ##-r ・・・検索対象にディレクトリを指定するとディレクトリ内のファイルを再帰的に検索してくれる [root@centos] # grep -r test . . /test1 :test1 . /dir1/test3 :test3 . /dir1/dir2/dir3/text4 .txt:test4 . /test2 :test2 |
1 2 3 4 | ##-n ・・・マッチした行と一緒に行番号を表示 [root@centos] # grep -n ntpd /var/log/messages 531:Jun 3 18:11:45 localhost ntpd[2211]: ntpd exiting on signal 15 818:Jun 3 18:14:17 localhost ntpd[2209]: ntpd 4.2.2p1@1.1570-o Thu Jan 22 02:51:26 UTC 2009 (1) |
1 2 3 4 5 6 7 | ##-h 複数のファイルを指定した場合に、抽出した行の先頭にファイル名を表示しない [root@centos] # grep test ./* . /test1 :test1 . /test2 :test2 [root@centos] # grep -h test ./* test1 test2 |