Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing match from grep in variable

I have the following extension: "/home/eg/Download/jdk-8u20-linux-x64.tar.gz"

I now want to pass the "jdk-8u20" to a separate variable.

the relevant regex in JS would be /jdk\-[0-9]u[0-9][0-9]?[0-9]?[0-9]?/

and I can get grep to acknowledge the data in question when i run the following on the command prompt:

test="/home/eg/Download/jdk-8u20-linux-x64.tar.gz"
grep jdk\-[0-9]u[0-9][0-9]*[0-9]*[0-9]* <(echo "$test")

but I can't figure out how to get that "jdk-8u20" into another variable!

i've tried

test1=${grep jdk\-[0-9]u[0-9][0-9]*[0-9]*[0-9]* <(echo "$test")}

but echo $test1 just returns the full file path. What do I need to do?

like image 694
Jay Edwards Avatar asked Sep 06 '25 03:09

Jay Edwards


1 Answers

You need to add the pattern within quotes and also you need to enable -o (show only the part of a line matching PATTERN) parameter.

$ test="/home/eg/Download/jdk-8u20-linux-x64.tar.gz"
$ test1=$(grep -o 'jdk-[0-9]u[0-9][0-9]*[0-9]*[0-9]*' <<< $test)
$ echo $test1
jdk-8u20
like image 163
Avinash Raj Avatar answered Sep 07 '25 21:09

Avinash Raj