如何在Shell脚本中使用正则表达式? [英] How do I use a regex in a shell script?
本文介绍了如何在Shell脚本中使用正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Shell脚本中将字符串与正则表达式匹配. 此字符串是脚本的参数($ 1),它是日期(MM/DD/YYYY) 我要使用的正则表达式是:
I am trying to match a string with a regex in a shell script. This string is a parameter of the script ( $1 ) and it is a date (MM/DD/YYYY) The regex I'm trying to use is :
^\d{2}[\/\-]\d{2}[\/\-]\d{4}$
似乎可行,我在多个正则表达式测试网站上进行了尝试.
It seems to work, I tried it on several regex tests websites.
我的shell代码是:
My shell code is :
REGEX_DATE="^\d{2}[\/\-]\d{2}[\/\-]\d{4}$"
echo "$1" | grep -q $REGEX_DATE
echo $?
回声$?"无论我输入的字符串是什么,都返回1.
The "echo $?" returns 1 no matter is the string I'm putting in parameter.
你们有个主意吗?
谢谢!
推荐答案
我认为这是您想要的:
REGEX_DATE='^\d{2}[/-]\d{2}[/-]\d{4}$'
echo "$1" | grep -P -q $REGEX_DATE
echo $?
我已经使用-P开关来获取perl regex.
I've used the -P switch to get perl regex.
这篇关于如何在Shell脚本中使用正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文