1
0

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.

zshの数値範囲指定の正規表現を使った

Posted at

#はじめに
シェルスクリプトのCase文で数値の範囲指定が使えないか検索してみたら,Zshの拡張正規表現ではそれが可能ということがわかったので,いろいろ試してみた.
#環境
Zsh 5.6.2
#使い方
###文法

<x-y>

これでx以上y以下の数値を指定できる.Zshのマニュアルによれば,xとyはそれぞれ省略可能,故に<->はあらゆる数にマッチする.
###使用例

#!/bin/zsh

foo=5

case "$foo" in
    <0-10> ) echo "aaa" ;;
    <11-20> ) echo "bbb" ;;
    <-> ) echo "ccc" ;;
esac
#=>aaa

temperature=40

case "$temperature" in
    <38-> ) echo "flu" ;;    # 38以上
    <-> ) echo "normal" ;;
esac
#=>flu

age=18

case "$age" in
    <-18> ) echo "child" ;;    #18以下
    <-> ) echo "adult" ;;
esac
#=>child

ちなみに負の数には対応していない模様.

#!/bin/zsh

water_temp=-30

case "$water_temp" in
    <-0> ) echo "solid" ;;
    <1-99> ) echo "liquid" ;;
    <100-> ) echo "gas" ;;
esac
#=>(何も表示されない)

負の数を判別したいなら,次の方法で行うという手がある.

#!/bin/zsh

negative_number=-30

case "$negative_number" in
    -<1-> ) echo "negative." ;;
    0 ) echo "zero." ;;
    <1-> ) echo "positive." ;;
esac
#=>negative.

また,正規表現であるゆえ,使用場面はCase文に限らない([1]).
#参考元
[1]zsh で「<>」を使って数値による範囲指定を行う - ablog
https://yohei-a.hatenablog.jp/entry/20090824/1251099682
[2]shell - case + how to implement equal or less or greater in case syntax - Unix & Linux Stack Exchange
https://unix.stackexchange.com/questions/65310/case-how-to-implement-equal-or-less-or-greater-in-case-syntax

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?