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.

shのパラメタ展開で遊ぶ

Last updated at Posted at 2019-05-14

##パターン置換相当を作る
dashとかだと前方一致部分の削除と後方一致部分の削除しかないので、

  • 先頭から置換したいパターンまでを削除した文字列
  • 置換したいパターンから末尾を削除した文字列

を用意してつなぎ合わせる。
bashとは異なり最短一致で置換する。

$ sub hogehoge hoge fuga
fugahoge
$ sub hogehoge 'o*e' age
hagehoge
$ sub hogehoge '*' h
hogehoge
$ gsub hogehoge hoge fuga
fugafuga
$ gsub hogehoge 'o*e' age
hagehage
$ gsub hogehoge '?' A
AAAAAAAA

コード

dashsub
if ! type return_val >/dev/null 2>&1; then
  alias return_val='echo'
fi

gsub() {
  case "$2"
  in *[!*]*) :
  ;; *)
    return_val "$1"
    return
  esac

  local h= v=$1
  while :; do
    case "$v"
    in *$2*)
      eval "h=\"$h\${v%%$2*}$3\""
      eval "v=\"\${v#*$2}\""
    ;; *)
      return_val "$h$v"
      break
    esac
  done
}

sub() {
  case "$2"
  in *[!*]*) :
  ;; *)
    return_val "$1"
    return
  esac

  case "$1"
  in *$2*) eval "echo \"\${1%%$2*}$3\${1#*$2}\""
  ;; *)    return_val "$1"
  esac
}

##部分文字列展開相当を作る

$ substr hogehoge 2 4
geho
$ substr hogehoge 4
hoge

コード

dashsub
if ! type return_val >/dev/null 2>&1; then
  alias return_val='echo'
fi

substr() {
  local t= str n=$2 m=${#1} l=$3
  if [ "$2" -ge "$m" ]; then
    return_val ""
    return
  fi
  if [ -z "$3" ]
    then l=0
    else l=$((m-n-l))
  fi
  while [ $n -gt 0 ]; do
    t=${t}?
    n=$((n-1))
  done
  eval "str=\"\${1#$t}\""
  t=
  while [ $l -gt 0 ]; do
    t=${t}?
    l=$((l-1))
  done
  eval "return_val \"\${str%$t}\""
}
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?