如何在Bash中将字符串与正则表达式匹配? [英] How can I match a string with a regex in Bash?

查看:356
本文介绍了如何在Bash中将字符串与正则表达式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个包含功能的bash脚本,因此当给定.tar.tar.bz2.tar.gz等文件时,它将使用tar和相关的开关来解压缩该文件.

I am trying to write a bash script that contains a function so when given a .tar, .tar.bz2, .tar.gz etc. file it uses tar with the relevant switches to decompress the file.

我正在使用if ifif then语句来测试文件名以查看其结尾,而我无法使用正则表达式元字符来匹配它.

I am using if elif then statements which test the filename to see what it ends with and I cannot get it to match using regex metacharacters.

为了避免经常在命令行中使用"test"重写脚本,我认为下面的语句应该可行,我尝试了可能的方括号,引号和元字符的每种组合,但仍然失败.

To save constantly rewriting the script I am using 'test' at the command line, I thought the statement below should work, I have tried every combination of brackets, quotes and metacharaters possible and still it fails.

test sed-4.2.2.tar.bz2 = tar\.bz2$; echo $?
(this returns 1, false)

我确定这个问题很简单,我到处都看过,但我无法理解该怎么做.有人知道我该怎么做吗?

I'm sure the problem is a simple one and I've looked everywhere, yet I cannot fathom how to do it. Does someone know how I can do this?

推荐答案

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

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.

这篇关于如何在Bash中将字符串与正则表达式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆