[victor@localhost ~]$ sh temp.sh string
String.
[victor@localhost ~]$ sh temp.sh 111
Others.
好了,加入 BASH_REMATCH
#!/bin/bash
# is this a string?
word=$1
if [ $# -eq 0 ] ; then
exit
fi
[[ "$word" =~ '\<[A-Za-z]+\>' ]] && echo 'String.' || echo 'Others.'
: ${BASH_REMATCH:?"no match"}
echo "Match: $BASH_REMATCH"
victor@localhost ~]$ sh temp.sh 111
Others.
temp.sh: line 8: BASH_REMATCH: no match
[victor@localhost ~]$ sh temp.sh who
String.
Match: who
[victor@localhost ~]$
bash 的 regexp 是使用跟 egrep相同的正規(guī)表示式,所以就不寫了,
請參考 CU 置頂?shù)奈恼?
最後我利用這個特性寫了一個名 count.sh 的樣版,它可計算文件某個
字符出現(xiàn)的次數(shù),本來以前需得用 awk, sed 的,在 3.0 以後不用了,也
不必呼叫外部程式,而且相當(dāng)簡單.
#! /bin/bash
# dep: Bash3.0 or above
# Purpose: Demo
# set Usage , pattern and file
pat=$1 ; file=$2
usage="Usage: ${0##*/} \"word\" file."
msg1="ex: ${0##*/} \"if\" ${0##*/}"
# if argument is not equal to 2 , print Usage and exit
if (( $# != 2 )) ; then
echo -e "$usage\n$msg1" >&2
exit 1
fi
# if $2 is not a regular file , print usage and exit
if [ ! -f "$file" ] ; then
echo -e "$usage\n$msg1" >&2
exit 1
fi
# set counter to zero
count=0
# search around the given file to match the given pattern
for i in $(<$file) ; do
if [[ "$i" =~ "\<$pat\>" ]] ; then
(( count += 1 )) # if matched, increase 1
fi
done