在bash中使用正则

我并不很喜欢用很复杂的正则,这会让程序可读性降低,更难维护。在使用工具的高级特性时,必须尽量维持代码的可维护性。

在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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值