简体   繁体   English

我可以在bash shell脚本中使用正则表达式吗

[英]can i use regex in a bash shell script

I am a first year Computer technician student, and before now have never actually used linux. 我是计算机技术员一年级的学生,在此之前从未真正使用过linux。 I grasped the basics of scripting fairly quickly and am trying to write a script that will create a directory and a soft link for each assignment. 我相当快地掌握了脚本编写的基础知识,并试图编写一个脚本,该脚本将为每个作业创建一个目录和一个软链接。 seeing as we average two assignments a week i thought this would be helpful. 看到我们平均每周有两次作业,我认为这会有所帮助。

I am having trouble making my script accept only numbers as variables. 我在使脚本只接受数字作为变量时遇到麻烦。 I have it mostly working (mostly) with use of 3 case statements, but would rather use basic regex with an if statement, if I can. 我主要使用3个case语句来工作(大部分),但是如果可以的话,我宁愿使用if语句使用基本的正则表达式。

if [ $# != 1 ]; then

    red='\033[0;31m'
    NC='\033[0m'
    blue='\033[1;34m'
    NC='\033[0m'
    echo 1>&2 "${blue}ERROR:${NC} $0 :${red}expecting only one variable, you gave $#($*)${NC}"
    echo 1>&2 "${blue}Usage:${NC} $0 :${red}number of assignment.${NC}"
    exit 2

fi


case $1 in

    [[:punct:]]*) echo 1>&2 "Numeric Values Only"
    exit 2
    ;;
    [[:alpha:]]*) echo 1>&2 "Numeric Values Only"
    exit 2
    ;;
    [[:space:]]*) echo 1>&2 "Numeric Values Only"
    exit 2
    ;;
esac

the script then makes the directory and creates a soft link for the marking script (if its posted), and ends. 然后,脚本创建目录并为标记脚本创建软链接(如果已发布),然后结束。 can anyone help me shorten/eliminate the case statements 谁能帮助我缩短/消除案件陈述

You cannot use regular expressions in portable shell scripts (ones that will run on any POSIX compliant shell). 您不能在可移植外壳脚本(将在任何POSIX兼容外壳上运行的脚本)中使用正则表达式。 In general, patterns in the shell are globs , not regular expressions. 通常,shell中的模式是glob ,而不是正则表达式。

That said, there are a few other options. 也就是说,还有其他一些选择。 If you are using Bash specifically, you have two choices; 如果您专门使用Bash,则有两种选择。 you can use extended globs, which give you some regex like functionality: 您可以使用扩展的glob,从而为您提供一些正则表达式之类的功能:

shopt -s extglob

case $1 in
    +([[:digit:]]) ) echo "digits" ;;
    *) echo "not digits" ;;
esac

Another option is that Bash has the =~ operator in the [[ ]] conditional construct to match strings against a regex; 另一种选择是Bash在[[ ]]条件结构中具有=~运算符,以将字符串与正则表达式进行匹配; this doesn't work in a case statement, but works in an if : 这在case语句中不起作用,但是在if起作用:

if [[ $1 =~ [0-9]+ ]]
then
    echo "digits"
fi

Finally, if you want to do regular expression matching portably (so it will run in other POSIX shells like ash , dash , ksh , zsh , etc), you can call out to grep ; 最后,如果您想方便地进行正则表达式匹配(因此它将在ashdashkshzsh等其他POSIX shell中运行),则可以调用grep if you pass -q , it will be silent about the matches but return success or failure depending on whether the input matched: 如果传递-q ,则将-q匹配,但根据输入是否匹配返回成功或失败:

if echo "$1" | grep -qE "[0-9]+"
then
    echo "digits"
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM