コンピュータリテラシー目次


便利なgrepの使い方

grepで正規表現を利用する
grepの利用の真骨頂は正規表現をパターンとして指定するときである. 以下,grepで使える正規表現パターンを説明する.

注意: 正規表現にはいくつかの派生版があり,コマンド grep, sed, awk, perl, ruby, emacs などによって使える正規表現は同じではない. たとえば,Emacsで使える正規表現は grep で使える正規表現よりも表現が豊かである.

理解しながら読み進むことが大切. (簡単なgrepの使い方も参考にせよ). 以下の説明で,半角空白文字を' 'で表すことがある.


演習
grepで正規表現を使うための次の演習ではgrepサンプルファイルをファイル名 grepsample.txt として適当なディレクトリに保存せよ.

次のgrepコマンドを実行し,その結果と示し,コマンドの意味を述べよ. オプション -n はマッチした行番号を表示するオプション.

  1. grep -n '\\' grepsample.txt
  2. grep -n '\^' grepsample.txt
  3. grep -n '\.$' grepsample.txt
  4. grep -n '^$' grepsample.txt
  5. grep -n ']' grepsample.txt
  6. grep -n '\[' grepsample.txt
  7. grep -n 'です。$' grepsample.txt
  8. grep -n '[0-9]' grepsample.txt
  9. grep -n '[A-Z]' grepsample.txt
  10. grep -n '\.' grepsample.txt
  11. grep -n '^[0-9]\. ' grepsample.txt
  12. grep -n '^[0-9]\.[0-9] ' grepsample.txt
  13. grep -n '[^a-zA-Z0-9]' grepsample.txt
  14. grep -n '\(Mac\).*\1' grepsample.txt

コンピュータリテラシー目次
mizutani@rsch.tuis.ac.jp