文字列の末尾でのマッチ
Bash の場合は以下のように glob を使えばできる。ただし glob を含む文字列ではダメ。
固定文字列であればエスケープすればよい。
code:ends_with_bash.sh
if "$target" = *some_str ; then ...
grep を使うとできるが、grep の正規表現を含む文字列ではダメ。
固定文字列であればエスケープすればよい。
code:ends_with_grep.sh
if $(printf "%s" "$target" | grep -qs "some_str\$"); then
以下のようにすれば変数に含まれる正規表現で使われるメタ文字をすべてエスケープできる。
code:escape_regex.sh
escaped_str=$(printf "%s" "$str" | sed -e 's/[]{}()*+?.\\^$|/\\&/g') grep による比較版
code:ends_with.sh
ends_with() (
printf "%s" "$1" | grep -qs $(printf "%s" "$2" | sed -e 's/[]{}()*+?.\\^$|/\\&/g')'$' )
愚直な比較版
code:ends_with.sh
ends_with() (
s1=$1
s2=$2
n1=${#s1}
n2=${#s2}
spos=$(($n1 - $n2))
return 1
fi
return
fi
sub1=$(echo $s1 | cut -c $((spos+1))-)
return
)