50
39

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.

Bashで正規表現マッチした文字列を取り出す

Posted at
#!/bin/bash

version="4.10.1"

if [[ ${version} =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
  all=${BASH_REMATCH[0]}
  major=${BASH_REMATCH[1]}
  minor=${BASH_REMATCH[2]}
  patch=${BASH_REMATCH[3]}

  echo ${all}    # 4.10.1
  echo ${major}  # 4
  echo ${minor}  # 10
  echo ${patch}  # 1
fi

ポイント

  • 比較部分は [[ ]] で囲う
  • 比較部分は =~
  • 右辺の正規表現部分は "" で囲わない
  • 右辺の正規表現部分でマッチさせて取り出したい部分をカッコで囲う
  • ${BASH_REMATCH[0]} にはマッチした文字列全体が入る
  • カッコで囲った部分が ${BASH_REMATCH[1]} 以降順番に得られる
50
39
0

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
50
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?