Karthik
Karthik

Reputation: 149

How to match a specific pattern in a longer string in bash?

I have a few files:

java-opentimelineio-0.14.0-beta-1-sources.jar
java-opentimelineio-0.14.0-beta-1.jar
java-opentimelineio-0.14.0.jar

I'm trying to use regex to match the file names like this:

find . -type f -name "[[:alnum:]]*[.][0-9]*(-beta-)?[0-9]*.jar"

I want the regex to match only these:

java-opentimelineio-0.14.0-beta-1.jar
java-opentimelineio-0.14.0.jar

But I'm getting no matches. From what I understand, a * after any character will match zero or more occurrences of that character and a ? will match zero or one occurrence of that character. Where am I going wrong?

Upvotes: 1

Views: 132

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626754

You can use

> find . -type f -regextype posix-egrep -regex '.*/[^/]+-[0-9]+\.[0-9]+\.[0-9]+(-beta-[0-9]+)?\.jar'
./java-opentimelineio-0.14.0-beta-1.jar
./java-opentimelineio-0.14.0.jar

Keep in mind that the regex can be used with -regex option and it must match the whole path.

The -regextype posix-egrep option allows using a "simpler" (meaning less escaping is involved) POSIX ERE engine .

Regex details:

  • .* - any zero or more chars
  • / - a / char
  • [^/]+ - one or more chars other than /
  • - - a hyphen
  • [0-9]+\.[0-9]+\.[0-9]+ - "version"-like pattern: one or more digits, ., one or more digits, ., one or more digits
  • (-beta-[0-9]+)? - an optional -beta- string and then one or more digits
  • \.jar - a .jar string.

Upvotes: 3

Related Questions