74
69

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

シェルスクリプトでの正規表現マッチ

Last updated at Posted at 2012-12-26

シェルスクリプトで正規表現でのマッチングを使いたい場合,少しぐぐってみると case 文を使えという内容のものがよくヒットするようですが,expr コマンドでも正規表現が使えます.

#!/bin/sh

if expr "aaabbc" : "b+c$" > /dev/null; then
    echo "hoge"
fi
# => hoge

正規表現を用いた場合,expr はマッチした位置や()でグループ化した結果を出力するので,要らない場合は /dev/null に捨てます.

ちなみに, zsh では [[ ]] を用いて自然に正規表現が書けます.

#!/usr/bin/zsh

if [[ "aaabbc" =~ "b+c$" ]]; then
    echo "hoge"
fi

bash の 3.1 以降ではクォートを付けてはいけないらしいです(コメント参照)
情報ありがとうございます.

74
69
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
74
69

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?