How can I match a string with a regex in Bash?

user1587462 picture user1587462 · Jul 2, 2013 · Viewed 306k times · Source

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.

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.

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?


dogbane picture dogbane · Jul 2, 2013

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

Try this:

[[ 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

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.