且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Bash中将字符串与正则表达式匹配?

更新时间:2023-09-03 21:53:46

要匹配正则表达式,您需要使用=~运算符.

To match regexes you need to use the =~ operator.

尝试一下:

[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched

或者,您可以使用==运算符使用通配符(而不是正则表达式):

Alternatively, you can use wildcards (instead of regexes) with the == operator:

[[ sed-4.2.2.tar.bz2 == *tar.bz2 ]] && echo matched

如果不考虑可移植性,我建议使用[[而不是[test,因为它更安全,功能更强大.有关详细信息,请参见测试[和[[[?]之间有什么区别.

If portability is not a concern, I recommend using [[ instead of [ or test as it is safer and more powerful. See What is the difference between test, [ and [[ ? for details.