Bash regex for just numbers and dots

Viewed 50

There's a folder with two files in it like: filename-3.0.1-extra.jar and filename-3.0.1.jar. The number and dots in the middle are the version, which can change. I'm trying to copy filename-3.0.1.jar to another folder. Something like:

cp folder1/filename-*.jar otherfolder/

But the wildcard * matches both files. I'm trying to copy just the file without the -extra at the end. So I'm trying to match filename on just numbers and dots when I copy, something like this:

cp folder1/filename-[0-9.].jar otherfolder/.

But that's not the right syntax for the regex. Would appreciate any help here!

UPDATE:

I got it somewhat working with this:

ls | grep -e "filename-[0-9]\.[0-9]\.[0-9]\.jar"

But the regex seems a bit rigid. Is there a way to shorten it to something like "filename-([0-9]+[\.])+jar"?

So that even cases like filename-32.430.3.jar would also get captured?

3 Answers

Using extglob you can do this:

shopt -s extglob
cp folder1/filename-+([0-9.]).jar otherfolder/

Here +([0-9.]) will match 1 or more of any digits or dots.


Based on your edited question it appears you're trying to use a grep with a regular expression. You can use this grep solution:

printf '%s\n' *.* | grep -E '^filename-([0-9]+\.)+jar$'

filename-3.0.1.jar

you can do something like

 cp "folder1/${##*.}" otherfolder

or

 cd folder1 && cp -r -v $(echo -e $(ls | grep -e "[0-9]*\.*")) otherfolder/. && cd ..

Given:

$ ls -1 *.jar
filename-3.0.1-extra.jar
filename-3.0.1.jar

You can use a loop and filter out those that match *-extra*:

for fn in *.jar; do   # with this glob, what DO you want
    [[ $fn != @(*-extra*) ]] && echo "$fn"   # and what you DONT want
done    

Prints:

filename-3.0.1.jar

So your loop could be:

for fn in *.jar; do
    [[ $fn != @(*-extra*) ]] && cp "$fn" otherfolder/
done    
Related