Unixコマンド/grep
grep †
機能 †
grepコマンドは、指定されたパターン(文字列)を含む行を抽出し、結果を標準出力に出力します。
ファイル名が指定されない場合は、標準入力からデータを読み込みます。
ファイル名はワイルドカードなどを用いて一度に複数のファイルを指定できます。
パターンには正規表現が指定できます。
形式 †
grep [オプション] [パターン] [ファイル名]
オプション †
-e このオプションに続く引数をパターンとして処理 (-から始まるパターンを指定したいときに使用) -h 複数のファイルを指定された場合でも、抽出した行の先頭にファイル名を表示しない -i パターンとの照合を行うときに、大文字小文字の区別をしない。 -n パターンを含む行がそのファイルに何行あるかを表示する。 -v 指定したパターンを含まない行を表示する。 -B1 指定したパターンを含む行と、その前1行を表示する。 -A1 指定したパターンを含む行と、その後一行を表示する。
コマンド例 †
▼指定した文字列を含む行を抽出
/etc/shellsからlocalを含む行を抽出
$ cat /etc/shells /etc/shellsの内容を表示する。 ------------------------------------------------- # $FreeBSD: src/etc/shells,v 1.3.2.1 2000/07/10 08:47:17 obrien Exp $ # # List of acceptable shells for chpass(1). # Ftpd will not allow users to connect who are not using # one of these shells. /bin/sh /bin/csh /bin/tcsh /usr/local/bin/bash ------------------------------------------------- $ grep local /etc/shells /usr/local/bin/bash
▼指定した文字列を含まない行を表示する。
/etc/shellsからlocalを含まない行を表示する。
$ grep -v local /etc/shells # $FreeBSD: src/etc/shells,v 1.3.2.1 2000/07/10 08:47:17 obrien Exp $ # # List of acceptable shells for chpass(1). # Ftpd will not allow users to connect who are not using # one of these shells. /bin/sh /bin/csh /bin/tcsh
▼正規表現を利用して、ある条件の文字列を抽出
/etc/shellsから行の先頭が/binで始まる行を抽出する。
$ grep -e ^/bin /etc/shells /bin/sh /bin/csh /bin/tcsh
▼指定したパターンの前2行を表示する。
$ cat /etc/passwd ---------------------------------------------- root:*:0:0:Charlie &:/root:/bin/csh toor:*:0:0:Bourne-again Superuser:/root: daemon:*:1:1:Owner of many system processes:/root:/usr/sbin/nologin operator:*:2:5:System &:/:/usr/sbin/nologin bin:*:3:7:Binaries Commands and Source:/:/usr/sbin/nologin tty:*:4:65533:Tty Sandbox:/:/usr/sbin/nologin kmem:*:5:65533:KMem Sandbox:/:/usr/sbin/nologin games:*:7:13:Games pseudo-user:/usr/games:/usr/sbin/nologin news:*:8:8:News Subsystem:/:/usr/sbin/nologin ---------------------------------------------- $ grep -B2 operator /etc/passwd toor:*:0:0:Bourne-again Superuser:/root: daemon:*:1:1:Owner of many system processes:/root:/usr/sbin/nologin operator:*:2:5:System &:/:/usr/sbin/nologin