我并不很喜欢用很复杂的正则,这会让程序可读性降低,更难维护。在使用工具的高级特性时,必须尽量维持代码的可维护性。
在bash中使用正则
基本都在grep awk 和sed上用正则,很少在bash中直接使用。
Since version 3 of bash (released in 2004) there is another option: bash's built-in regular expression comparison operator "=~".
这里做个很简略的笔记。
关键词:正则 脚本
key words: bash , regular expressions, re
判断某变量是否英文字符串:
正则:
if [[ $a =~ ^[a-zA-Z]+$ ]] ; then echo "is alpha"; fi
if [[ $a =~ ^[[:alpha:]]+$ ]] ; then echo "is alpha"; fi
通配:
if [[ -n $a && ! $a = *[!a-zA-Z]* ]] ; then echo "is alpha"; fi
判断某变量是否数字字符串:???留题
匹配子串:BASH_REMATCH
#!/bin.bash
if [[ $# -lt 2 ]]; then
echo "Usage: $0 PATTERN STRINGS..."
exit 1
fi
regex=$1
shift
echo "regex: $regex"
echo
while [[ $1 ]]
do
if [[ $1 =~ $regex ]]; then
echo "$1 matches"
i=1
n=${#BASH_REMATCH[*]}
while [[ $i -lt $n ]]
do
echo " capture[$i]: ${BASH_REMATCH[$i]}"
let i++
done
else
echo "$1 does not match"
fi
shift
done
Assuming the script is saved in "bashre.sh", the following sample shows its output:
# sh bashre.sh 'aa(b{2,3}[xyz])cc' aabbxcc aabbcc
regex: aa(b{2,3}[xyz])cc
aabbxcc matches
capture[1]: bbx
aabbcc does not match
在bash中使用正则
基本都在grep awk 和sed上用正则,很少在bash中直接使用。
Since version 3 of bash (released in 2004) there is another option: bash's built-in regular expression comparison operator "=~".
这里做个很简略的笔记。
关键词:正则 脚本
key words: bash , regular expressions, re
判断某变量是否英文字符串:
正则:
if [[ $a =~ ^[a-zA-Z]+$ ]] ; then echo "is alpha"; fi
if [[ $a =~ ^[[:alpha:]]+$ ]] ; then echo "is alpha"; fi
通配:
if [[ -n $a && ! $a = *[!a-zA-Z]* ]] ; then echo "is alpha"; fi
判断某变量是否数字字符串:???留题
匹配子串:BASH_REMATCH
#!/bin.bash
if [[ $# -lt 2 ]]; then
echo "Usage: $0 PATTERN STRINGS..."
exit 1
fi
regex=$1
shift
echo "regex: $regex"
echo
while [[ $1 ]]
do
if [[ $1 =~ $regex ]]; then
echo "$1 matches"
i=1
n=${#BASH_REMATCH[*]}
while [[ $i -lt $n ]]
do
echo " capture[$i]: ${BASH_REMATCH[$i]}"
let i++
done
else
echo "$1 does not match"
fi
shift
done
Assuming the script is saved in "bashre.sh", the following sample shows its output:
# sh bashre.sh 'aa(b{2,3}[xyz])cc' aabbxcc aabbcc
regex: aa(b{2,3}[xyz])cc
aabbxcc matches
capture[1]: bbx
aabbcc does not match